diff --git a/AGENTS.md b/AGENTS.md index 6775f60..ba6fa8b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,19 +58,19 @@ The Architecture Map below describes pine and the shared packages. | `navigation.go` | Screen routing via back stack, propagateSize (sets all 8 screen models), initScreen, updateScreen dispatch | | `render.go` | View composition: header + error banner + screen + hints + player footer + chapter overlay modal + confirmation overlay | | `bookmarks.go` | Bookmark CRUD, chapter next/prev, seek logic (in-track vs cross-track), fetchBookmarksCmd/fetchEpisodesCmd/fetchBookDetailCmd | -| `metadata.go` | Metadata editor save flow: server PATCH, cache eviction, detail refresh | +| `metadata.go` | Metadata editor save flow: server PATCH, cache eviction, search snapshot prewarm, detail refresh | | `messages.go` | Screen enum, PlaySessionMsg, PlaySessionData, QueueEntry, all root-level message types | | `keymap.go` | Global keybindings (quit, back, help, chapter overlay, queue, sleep, command palette). Key names for the player model. | | `help.go` | Help overlay groups for pine | | `sessions.go` | The `R` key and the palette entries for listening sessions: the target of the detail screen, the item that plays, or all items. The jump from a session: a seek, or a fetch of the item and `playItemAt`. | | `queue.go` | Queue entry enqueue/dequeue with dedup, clone helpers | -| `mpris_state.go` | MPRIS bridge message conversion between player state and D-Bus adapter | +| `mpris_state.go` | `MprisState`: the playback state that the MPRIS server reads through `mpris.ModelAccessor` | ### Player (internal/player/, shared) | File | Responsibility | |------|---------------| -| `mpv.go` | Mpv struct: Launch (creates a libmpv handle and loads the file), GetPosition/GetDuration/GetPaused/GetIdle, Seek, SetSpeed/SetVolume, Quit. `ErrClosed` and `ErrPropertyUnavailable`. Writes the warnings and errors of mpv to the app log, without URL queries. Runtime directory for the media cache. | +| `mpv.go` | Mpv struct: Launch (creates a libmpv handle and loads the file), GetPosition/GetDuration/GetPaused/GetIdle, Seek, SetSpeed/SetVolume, Quit. `ErrClosed` and `ErrPropertyUnavailable`. Writes the warnings and errors of mpv to the app log, without the query, the user, or the password of a URL. Runtime directory for the media cache. | | `libmpv.go`, `libmpv_unix.go`, `libmpv_windows.go` | Binding to libmpv through purego, with no cgo. The library loads on the first Launch. Library search order for each system. | | `commands.go` | tea.Cmd factories: TickCmd (500ms poll), TickAfterCmd (poll after an interval), LaunchCmd, SetPauseCmd, SetSpeedCmd, SetVolumeCmd, QuitCmd. A command for the pause state, the speed, or the volume returns CommandErrMsg if the player does not accept the value. WatchEvents returns PlayerEndMsg at the end of a playback. | | `model.go` | Player sub-model: Position/Duration/Speed/Volume state, key handling (play/pause, seek, speed, volume) | @@ -89,24 +89,24 @@ The Architecture Map below describes pine and the shared packages. | `serieslist` | model.go | Paginated series browser (50/page), infinite scroll. | | `series` | model.go | Books within a series, sorted by sequence number. Highlights current item, prefixes finished books with ✓. | | `sessions` | model.go | Listening sessions of a book, a podcast episode, or all items (50 newest). Each row shows the end position, the device, and the time of the last sync. Enter sends `PlayFromMsg`. | -| `search` | cache.go | No longer a standalone screen. Fuzzy-search cache used by the command palette and shared with the library view. Builds full library snapshots (all items fetched, normalized, tokenized) with background pre-warm. | +| `search` | cache.go | No longer a standalone screen. Fuzzy-search cache used by the command palette and shared with the library view. Builds full library snapshots (all items fetched, normalized, tokenized) with background pre-warm. `Search` answers only from a ready snapshot in memory or in SQLite. On a miss, it returns no results and builds the snapshot in the background, so the palette does not wait for the network in `Update`. When the palette opens and the snapshot of its library is not ready, `openGlobalPalette` returns `PrebuildCmd`. On `CacheReadyMsg` for that library, `Palette.Refresh` applies the query again and shows the results. An invalidation removes the builds in flight, so a build that started before a change stores nothing. | ### Cache (internal/cache/) | File | Responsibility | |------|---------------| -| `client.go` | Cached wrapper around `abs.Client`: serves cache hits instantly, falls back to API, and triggers background rebuilds. Each cached method calls `cached(c, key, ttl, fetch)`, which returns the data of the server. A cache read or write error goes to the log and does not fail the request. | -| `keys.go` | The names of all cache keys. Code outside the package uses `ItemKey`, `PersonalizedKey`, `SeriesContentsKey`, `BookmarksKey`, and `SearchSnapshotKey`, not key strings. | +| `client.go` | Cached wrapper around `abs.Client`: serves cache hits instantly. On a miss, it fetches from the API in the command of the caller and stores the result. Each cached method calls `cached(c, key, ttl, fetch)`, which returns the data of the server. A cache read or write error goes to the log and does not fail the request. A fetch that started before an invalidation does not store its value (`generation`, under `mu`). `invalidate` calls `OnInvalidate` also when the store is nil. | +| `keys.go` | The names of all cache keys. Code outside the package uses `ItemKey`, `PersonalizedKey`, `SeriesContentsKey`, `BookmarksKey`, and `SearchSnapshotKey`, not key strings. A key has no account, so a login (`LoginSuccessMsg`) clears the persistent cache with `ClearAll`. | | `store.go` | SQLite-backed cache persistence and `ClearAll`. Each key in the database has the prefix `keyVersion` (`v1-`). Raise it when the type of a cached value changes. | ### MPRIS (internal/mpris/, shared) | File | Responsibility | |------|---------------| -| `adapter.go` | D-Bus MPRIS adapter exposing playback status, metadata, and seek controls. | -| `bridge.go` | Bubbletea message bridge between the MPRIS adapter and root model. | +| `adapter.go` | `RootAdapter` (`CanQuit` and `CanRaise` are false), the playback status and the track metadata from the app state, `trackPath`, and `PlayerActions`. | +| `bridge.go` | Bubbletea message bridge between the MPRIS server and root model. A rate of 0 pauses. A rate is limited to `MinimumRate`..`MaximumRate`, and a volume to 0..1.5. `SetPosition` ignores a position outside the track. With skip seek, `CanGoNext` and `CanGoPrevious` are `HasActiveItem` and `CanSeek`. | | `accessor.go` | Read-only MPRIS property accessor. | -| `server.go` | MPRIS server on `godbus/dbus`: the root and player interfaces, the D-Bus properties interface, introspection, and the change signals. | +| `server.go` | MPRIS server on `godbus/dbus`: the root and player interfaces, the D-Bus properties interface, introspection, and the change signals. `NewServer(name, root, accessor, actions)` reads the player properties from `ModelAccessor` and calls `PlayerActions`. It rejects a Rate or a Volume value that is not finite. `CanPlay` and `CanPause` are `HasActiveItem`, and `StatusChanged` and `PlaybackChanged` send them. `StatusChanged` and `PlaybackChanged` also send `CanGoNext` and `CanGoPrevious`. | The server is written from the MPRIS 2.2 specification. The Go MPRIS server library that exists is GPL-3.0, and a GPL module makes the release binaries GPL. Do not add a module with a copyleft license. @@ -114,17 +114,17 @@ The server is written from the MPRIS 2.2 specification. The Go MPRIS server libr | File | Responsibility | |------|---------------| -| `client.go` | HTTP client with 10s timeout, 50MB response limit, auth header, request logging | +| `client.go` | HTTP client with 10s timeout, 50MB response limit, auth header, request logging. `NewClient` removes the spaces and the trailing slashes of the server address. `HTTPStatusError` keeps at most 500 bytes of the response body. A log line or a request error shows `SessionTag` (a short hash) in place of a play session ID. | | `types.go` | All ABS data types. Custom UnmarshalJSON for MediaMetadata.Series (handles both object and array). | | `libraries.go` | GetLibraries, GetPersonalized, GetLibraryItems (paginated), GetLibraryItemsBatch (10 concurrent), GetLibrarySeries, GetSeriesContents, FilterAudioLibraries (sample-based audio detection) | | `playback.go` | StartPlaySession, StartEpisodePlaySession, SyncSession, CloseSession, CloseSessionNoSync (sends no position) | -| `progress.go`, `me.go` | UpdateProgress, UpdatePosition (no `isFinished` key), GetMediaProgress (ABS gives no bookmarks with the progress), UpdateEpisodeProgress, GetMe (user + all media progress) | +| `progress.go`, `me.go` | UpdateProgress, UpdatePosition (no `isFinished` key), GetMediaProgress (ABS gives no bookmarks with the progress), GetMe (user + all media progress). UpdateProgress and UpdatePosition take an episode ID for a podcast episode. | | `sessions.go` | GetListeningSessions (`GET /api/me/listening-sessions`), GetItemListeningSessions (`GET /api/me/item/listening-sessions/{id}[/{episodeId}]`) | | `bookmarks.go` | CreateBookmark, UpdateBookmark, DeleteBookmark, GetBookmarks (`GET /api/me/bookmarks/{id}`, or `GET /api/me` for ABS before 2.36.0) | ### Data (internal/db/) -SQLite store (WAL mode) for accounts and listening sessions. `busy_timeout` is 5000 ms, so a write waits while a different connection writes. Single "last" session row for crash recovery. +SQLite store (WAL mode) for accounts and listening sessions. `busy_timeout` is 5000 ms, so a write waits while a different connection writes. Single "last" session row for crash recovery. It keeps only the item ID and the episode ID. The restore gets the position from the server. The accounts table keeps only the account of the last login, because `SaveAccount` deletes the other accounts. ### Config (internal/config/) @@ -141,7 +141,7 @@ Styles from theme config. Format helpers (timestamps, durations). `RunProgram` r - All async work in `tea.Cmd` closures captures needed values by copy, never model references - `tea.Batch` for concurrent async operations - Skeleton loading with generation-gated reveal delays (home: 500ms, library: 150ms) -- Cache-first data loading through `internal/cache.Client`: home and library views hit the persistent cache first; misses trigger a background rebuild +- Cache-first data loading through `internal/cache.Client`: home and library views hit the persistent cache first. A miss fetches from the server in the command of the caller and stores the result. - `q` quits, and `esc`/left goes back (never quits). `h`/`l` seek only, arrows navigate only. These keys have no global function while a text input or a dialog gets the keys (`capturesKeys`). - A quit (`q` or ctrl+c) returns only `tea.Quit` and keeps the session in the model. `Cleanup` sends the last position, and `main` waits for it. Bubble Tea does not wait for a command at a quit, so a quit must not send the position in a command. - The `main` of pine and the `main` of spruce run the program with `ui.RunProgram`, which quits the program at SIGHUP, the close of the terminal, so that `Cleanup` runs. Bubble Tea quits the program at SIGTERM. @@ -153,6 +153,9 @@ Styles from theme config. Format helpers (timestamps, durations). `RunProgram` r - pine finds the end of a track through `errors.Is(err, player.ErrClosed)` on a position tick. spruce uses `PlayerEndMsg`, and a tick with `ErrClosed` can arrive before it. Do not match the text of a player error. - Enter on a bookmark (`handleSeekToBookmark`) seeks the player only if the book or the episode of the bookmark plays. If not, it stops the playback and starts that book or that episode at the time of the bookmark. - A bookmark of ABS has no episode ID. `handleAddBookmark` puts the episode title and `episodeTitleSeparator` before the title of a podcast bookmark, and `bookmarkEpisode` finds the episode from that title. The bookmarks on a server have that format, so do not change it. +- The copies of the root model share the MPRIS bridge through `mprisLink`, because `main` calls `SetProgram` after `tea.NewProgram` copies the model. Reach the bridge through `mprisBridge()`. +- pine writes the MPRIS position to `MprisState` on each position tick. It sends the MPRIS signal Seeked only for a seek (`seekToBookGlobalPosition`), for a playback that starts at a position after 0, and for a restart of the same item (`restartPlaybackAt`) at each position, because the track ID does not change. It does not send Seeked as a periodic position report. +- `isUnauthorized` finds a 401 with `abs.IsHTTPStatus(err, http.StatusUnauthorized)`. A test that needs a 401 uses `&abs.HTTPStatusError{StatusCode: http.StatusUnauthorized}`, not an error text. ## Testing @@ -163,8 +166,9 @@ Styles from theme config. Format helpers (timestamps, durations). `RunProgram` r - `internal/app/model_test.go`, `playback_test.go`, `bookmarks_test.go`, `render_test.go` for app-level tests - `internal/ui/program_unix_test.go` starts the test program again as a child process, sends SIGHUP to it, and checks that it gets to the place where a `main` calls `Cleanup`. The child runs its program with `ui.RunProgram`, as each `main` does. It does not run on Windows. - `internal/cache/*_test.go` for cache store and helper behavior -- `internal/mpris/mpris_test.go` for the D-Bus adapter and bridge +- `internal/mpris/mpris_test.go` for `RootAdapter` and the server properties, and `bridge_test.go` for the bridge - `internal/mpris/server_linux_test.go` starts the MPRIS server on a private session bus and checks it as an MPRIS client. It skips if `dbus-daemon` is absent. With `PINE_REQUIRE_DBUS=1` it fails instead. CI and `scripts/release.sh` set that variable. +- `internal/app/mpris_linux_test.go` starts the MPRIS server of the pine model on a private session bus and checks the Seeked signals. It skips if `dbus-daemon` is absent. With `PINE_REQUIRE_DBUS=1` it fails instead. - `internal/screens/metadataedit/model_test.go` for the metadata editor - Screen models have individual `*_test.go` files - `internal/player/libmpv_test.go`, `mpv_test.go`, and `group_test.go` play audio through the real libmpv with `ao=null`. They skip if libmpv is absent. With `PINE_REQUIRE_LIBMPV=1` they fail instead. `scripts/release.sh` sets that variable. @@ -172,4 +176,4 @@ Styles from theme config. Format helpers (timestamps, durations). `RunProgram` r ## Logging -Logs to `~/.config/pine/pine.log` (slog-based, auto-rotated at 5MB). Token/credentials are NOT logged. spruce logs to `spruce.log` in its config directory. +Logs to `~/.config/pine/pine.log` (slog-based). At start, `Init` renames `.log` to `.log.old` when the file is over 5 MB, and only while it holds the lock of the file. An instance that cannot lock the log writes to `-.log`. Token/credentials are NOT logged. A play session ID gives the audio of the session with no login, so pine logs only `abs.SessionTag(id)` in the field `session`, never the full ID. spruce logs to `spruce.log` in its config directory. diff --git a/README.md b/README.md index 9e8e1fc..280db25 100644 --- a/README.md +++ b/README.md @@ -138,10 +138,11 @@ error = "#e67e80" muted = "#859289" selected = "#475258" border = "#4f585e" -warning = "#dbbc7f" info = "#7fbbb3" ``` +`player.speed` must be from 0.1 to 100, and `player.seek_seconds` must be more than 0. For a different value, pine stops at startup with an error that names the key. + Pine creates a stable playback identity on first run: ```toml @@ -156,6 +157,10 @@ display-only and can be changed without changing `device_id`. Audiobookshelf displays this as `Pine ` (without Pine's default `(Pine)` suffix), for example `Pine my-host`. +Pine writes a generated `device_name` and `device_id` to `config.toml`. A +read-only `config.toml`, for example a home-manager symlink, must set the two +keys, or Pine cannot start. + Pine sends its Go module build version as `clientVersion` to Audiobookshelf. Local development builds report `dev`. diff --git a/docs/spruce/README.md b/docs/spruce/README.md index c1f1be2..641a439 100644 --- a/docs/spruce/README.md +++ b/docs/spruce/README.md @@ -77,8 +77,8 @@ and the file uses mode `0600`; local file permissions are the security boundary. See [Auth token storage](../design/spruce/auth-token-storage.md) for the decision and operational details. -Logs are written to the same config directory as `spruce.log` and rotated after -5 MB. +Logs are written to the same config directory as `spruce.log` and rotated at +start when the file is over 5 MB. ## Common keybindings @@ -94,11 +94,12 @@ Keys can be context-specific. Press `?` in Spruce for the complete active help. | `space` | Play or pause | | `h` / `l` | Seek backward or forward | | `n` / `>` | Next track | -| `N` / `p` / `<` | Previous track | +| `N` / `p` / `<` | Previous track in the first 3 seconds of a track. Later, or at the first track, play the track again from the start. | | `a` / `A` | Add selected track or collection to the queue | -| `S` | Shuffle selected collection or cycle the sleep timer | +| `S` | On the library and playlists screens: add the selected album or playlist to the queue in shuffled order | +| `S` | On the queue screen during playback: cycle the sleep timer. The command palette also sets it. | | `s` | Shuffle the current queue | -| `r` / `R` | Repeat current track or queue | +| `r` / `R` | Repeat a track or the queue. On the queue screen, `r` repeats the selected track. On the other screens, it repeats the track that plays. | | `b` | Toggle subliminal mode from the queue | | `+` / `-` | Increase or decrease playback speed | | `]` / `[` | Increase or decrease volume | @@ -109,6 +110,8 @@ Keys can be context-specific. Press `?` in Spruce for the complete active help. | `ctrl+p` | Open the command palette | | `?` | Toggle help | +With queue repeat, the next track key at the last track plays the first track. + ## Repeat cache and subliminal mode When track or queue repeat is active, Spruce downloads repeated media into a @@ -151,6 +154,11 @@ sleep_timer = "S" back = "esc" ``` +On the library and playlists screens, `S` adds the selection to the queue in +shuffled order. With `sleep_timer = "S"`, the sleep timer key does not work on +these two screens. To use the sleep timer key on each screen, set a different +key. + The generated `[theme]` section contains the editable Everforest color values. See [Theme configuration](../design/spruce/theme-configuration.md) for the supported scope. diff --git a/internal/abs/client.go b/internal/abs/client.go index f874fc7..a6f79dd 100644 --- a/internal/abs/client.go +++ b/internal/abs/client.go @@ -3,11 +3,15 @@ package abs import ( "bytes" "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "fmt" "io" "net/http" + "net/url" + "strings" "sync/atomic" "time" @@ -17,7 +21,8 @@ import ( // HTTPStatusError wraps a non-2xx HTTP response status. type HTTPStatusError struct { StatusCode int - Body string + // Body is the start of the response body, at most 500 bytes. + Body string } func (e *HTTPStatusError) Error() string { @@ -42,10 +47,12 @@ type Client struct { noBookmarkRoute atomic.Bool } -// NewClient creates a new ABS API client. +// NewClient creates a new ABS API client. It removes the spaces around +// baseURL and the slashes at its end, so that a request path does not start +// with "//". func NewClient(baseURL, token string) *Client { return &Client{ - baseURL: baseURL, + baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"), token: token, httpClient: &http.Client{ Timeout: 10 * time.Second, @@ -75,9 +82,14 @@ func (c *Client) do(ctx context.Context, method, path string, body any) ([]byte, req.Header.Set("Authorization", "Bearer "+c.token) } + shownPath := logPath(path) resp, err := c.httpClient.Do(req) if err != nil { - logger.Error("http request failed", "method", method, "path", path, "err", err, "duration", time.Since(start)) + var urlErr *url.Error + if errors.As(err, &urlErr) { + urlErr.URL = strings.Replace(urlErr.URL, path, shownPath, 1) + } + logger.Error("http request failed", "method", method, "path", shownPath, "err", err, "duration", time.Since(start)) return nil, fmt.Errorf("execute request: %w", err) } defer func() { _ = resp.Body.Close() }() @@ -85,20 +97,21 @@ func (c *Client) do(ctx context.Context, method, path string, body any) ([]byte, limitedReader := io.LimitReader(resp.Body, maxResponseSize+1) data, err := io.ReadAll(limitedReader) if err != nil { - logger.Error("http response read failed", "method", method, "path", path, "status", resp.StatusCode, "err", err, "duration", time.Since(start)) + logger.Error("http response read failed", "method", method, "path", shownPath, "status", resp.StatusCode, "err", err, "duration", time.Since(start)) return nil, fmt.Errorf("read response body: %w", err) } if len(data) > maxResponseSize { - logger.Error("http response body too large", "method", method, "path", path, "status", resp.StatusCode, "limit", maxResponseSize, "duration", time.Since(start)) + logger.Error("http response body too large", "method", method, "path", shownPath, "status", resp.StatusCode, "limit", maxResponseSize, "duration", time.Since(start)) return nil, fmt.Errorf("response body exceeds %d byte limit", maxResponseSize) } if resp.StatusCode < 200 || resp.StatusCode >= 300 { - logger.Error("http request returned unexpected status", "method", method, "path", path, "status", resp.StatusCode, "body", truncateLogBody(data), "duration", time.Since(start)) - return nil, &HTTPStatusError{StatusCode: resp.StatusCode, Body: string(data)} + body := truncateLogBody(data) + logger.Error("http request returned unexpected status", "method", method, "path", shownPath, "status", resp.StatusCode, "body", body, "duration", time.Since(start)) + return nil, &HTTPStatusError{StatusCode: resp.StatusCode, Body: body} } - logger.Debug("http request completed", "method", method, "path", path, "status", resp.StatusCode, "duration", time.Since(start)) + logger.Debug("http request completed", "method", method, "path", shownPath, "status", resp.StatusCode, "duration", time.Since(start)) return data, nil } @@ -136,6 +149,30 @@ func (c *Client) Token() string { return c.token } +// SessionTag returns a short name for the ID of a play session, for a log +// line. The ID gives the audio of the session with no login, so a log line +// must not contain it. The same ID gives the same name. +func SessionTag(id string) string { + sum := sha256.Sum256([]byte(id)) + return "#" + hex.EncodeToString(sum[:3]) +} + +// sessionPathPrefix starts the path of each request about one play session. +const sessionPathPrefix = "/api/session/" + +// logPath returns path with the ID of a play session replaced by its tag. +func logPath(path string) string { + rest, ok := strings.CutPrefix(path, sessionPathPrefix) + if !ok { + return path + } + end := strings.IndexByte(rest, '/') + if end < 0 { + end = len(rest) + } + return sessionPathPrefix + SessionTag(rest[:end]) + rest[end:] +} + func truncateLogBody(data []byte) string { const max = 500 if len(data) <= max { diff --git a/internal/abs/client_test.go b/internal/abs/client_test.go index 3cf4ecc..2decae9 100644 --- a/internal/abs/client_test.go +++ b/internal/abs/client_test.go @@ -126,3 +126,41 @@ func TestLoginDeserializesToken(t *testing.T) { t.Errorf("client token not updated: got %q", c.token) } } + +func TestNewClientTrimsTheServerAddress(t *testing.T) { + var gotPath string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + _, _ = w.Write([]byte(`{"user": {"token": "tok"}}`)) + })) + defer srv.Close() + + c := NewClient(" "+srv.URL+"/ ", "") + if _, err := c.Login(context.Background(), "admin", "secret"); err != nil { + t.Fatalf("Login() returned error: %v", err) + } + if gotPath != "/login" { + t.Errorf("request path = %q, want /login", gotPath) + } + if c.BaseURL() != srv.URL { + t.Errorf("BaseURL() = %q, want %q", c.BaseURL(), srv.URL) + } +} + +func TestDoKeepsAShortBodyInTheStatusError(t *testing.T) { + page := strings.Repeat("

Bad Gateway

", 10000) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusBadGateway) + _, _ = w.Write([]byte(page)) + })) + defer srv.Close() + + c := NewClient(srv.URL, "tok") + _, err := c.do(context.Background(), http.MethodGet, "/api/items/a", nil) + if !IsHTTPStatus(err, http.StatusBadGateway) { + t.Fatalf("do() error = %v, want the status 502", err) + } + if len(err.Error()) > 600 { + t.Errorf("len(err.Error()) = %d, want at most 600", len(err.Error())) + } +} diff --git a/internal/abs/files.go b/internal/abs/files.go index d2ad143..9485cf9 100644 --- a/internal/abs/files.go +++ b/internal/abs/files.go @@ -7,17 +7,13 @@ import ( "net/http" "path/filepath" "strings" - - "github.com/Thelost77/pine/internal/logger" ) // GetLibraryFiles returns libraryFiles from an expanded item without storing the item. func (c *Client) GetLibraryFiles(ctx context.Context, itemID string) ([]LibraryFile, error) { path := fmt.Sprintf("/api/items/%s?expanded=1", itemID) - logger.Debug("API request", "method", "GET", "path", path, "itemID", itemID) data, err := c.do(ctx, http.MethodGet, path, nil) if err != nil { - logger.Error("get library files failed", "itemID", itemID, "err", err) return nil, fmt.Errorf("get library files: %w", err) } var resp struct { @@ -32,10 +28,8 @@ func (c *Client) GetLibraryFiles(ctx context.Context, itemID string) ([]LibraryF // GetLibraryFile downloads a library file by inode. func (c *Client) GetLibraryFile(ctx context.Context, itemID, ino string) ([]byte, error) { path := fmt.Sprintf("/api/items/%s/file/%s", itemID, ino) - logger.Debug("API request", "method", "GET", "path", path, "itemID", itemID, "ino", ino) data, err := c.do(ctx, http.MethodGet, path, nil) if err != nil { - logger.Error("get library file failed", "itemID", itemID, "ino", ino, "err", err) return nil, fmt.Errorf("get library file: %w", err) } return data, nil diff --git a/internal/abs/filter_test.go b/internal/abs/filter_test.go index bbbe24c..7fbe551 100644 --- a/internal/abs/filter_test.go +++ b/internal/abs/filter_test.go @@ -16,10 +16,7 @@ func TestFilterAudioLibraries_KeepsPodcasts(t *testing.T) { c := NewClient(srv.URL, "tok") libs := []Library{{ID: "pod-1", Name: "Podcasts", MediaType: "podcast"}} - result, err := c.FilterAudioLibraries(context.Background(), libs) - if err != nil { - t.Fatal(err) - } + result := c.FilterAudioLibraries(context.Background(), libs) if len(result) != 1 { t.Fatalf("expected 1 library, got %d", len(result)) } @@ -48,10 +45,7 @@ func TestFilterAudioLibraries_KeepsAudiobooks(t *testing.T) { c := NewClient(srv.URL, "tok") libs := []Library{{ID: "audio-lib", Name: "Audiobooks", MediaType: "book"}} - result, err := c.FilterAudioLibraries(context.Background(), libs) - if err != nil { - t.Fatal(err) - } + result := c.FilterAudioLibraries(context.Background(), libs) if len(result) != 1 { t.Fatalf("expected audiobook library to be kept, got %d libraries", len(result)) } @@ -79,10 +73,7 @@ func TestFilterAudioLibraries_ExcludesEbooks(t *testing.T) { c := NewClient(srv.URL, "tok") libs := []Library{{ID: "ebook-lib", Name: "Books", MediaType: "book"}} - result, err := c.FilterAudioLibraries(context.Background(), libs) - if err != nil { - t.Fatal(err) - } + result := c.FilterAudioLibraries(context.Background(), libs) if len(result) != 0 { t.Fatalf("expected ebook library to be excluded, got %d libraries", len(result)) } @@ -105,10 +96,7 @@ func TestFilterAudioLibraries_DetectsAudioByNumTracks(t *testing.T) { c := NewClient(srv.URL, "tok") libs := []Library{{ID: "lib-1", Name: "Books with Audio", MediaType: "book"}} - result, err := c.FilterAudioLibraries(context.Background(), libs) - if err != nil { - t.Fatal(err) - } + result := c.FilterAudioLibraries(context.Background(), libs) if len(result) != 1 { t.Fatal("expected library with numTracks>0 to be kept") } @@ -131,10 +119,7 @@ func TestFilterAudioLibraries_DetectsAudioByNumAudioFiles(t *testing.T) { c := NewClient(srv.URL, "tok") libs := []Library{{ID: "lib-1", Name: "Audiobooks", MediaType: "book"}} - result, err := c.FilterAudioLibraries(context.Background(), libs) - if err != nil { - t.Fatal(err) - } + result := c.FilterAudioLibraries(context.Background(), libs) if len(result) != 1 { t.Fatal("expected library with numAudioFiles>0 to be kept") } diff --git a/internal/abs/libraries.go b/internal/abs/libraries.go index a0507df..aab9cae 100644 --- a/internal/abs/libraries.go +++ b/internal/abs/libraries.go @@ -81,9 +81,6 @@ func (c *Client) GetPersonalized(ctx context.Context, libraryID string) ([]Perso // recentEpisodeResponse is the ABS response shape for GET /api/libraries/{id}/recent-episodes. type recentEpisodeResponse struct { Episodes []recentEpisodeEntry `json:"episodes"` - Total int `json:"total"` - Limit int `json:"limit"` - Page int `json:"page"` } // recentEpisodeEntry represents a single episode in the recent-episodes response. @@ -134,14 +131,6 @@ func (c *Client) GetRecentEpisodes(ctx context.Context, libraryID string, limit items := make([]LibraryItem, 0, len(resp.Episodes)) for _, ep := range resp.Episodes { authorName := ep.Podcast.Metadata.Author - var index *int - if ep.Index != nil { - index = ep.Index - } - var publishedAt *int64 - if ep.PublishedAt != nil { - publishedAt = ep.PublishedAt - } items = append(items, LibraryItem{ ID: ep.LibraryItemID, MediaType: "podcast", @@ -155,11 +144,11 @@ func (c *Client) GetRecentEpisodes(ctx context.Context, libraryID string, limit }, RecentEpisode: &PodcastEpisode{ ID: ep.ID, - Index: index, + Index: ep.Index, Title: ep.Title, Description: ep.Description, Duration: ep.Duration, - PublishedAt: publishedAt, + PublishedAt: ep.PublishedAt, AddedAt: ep.AddedAt, }, }) @@ -174,26 +163,6 @@ func strPtr(s string) *string { return &s } -// GetRecentlyAdded fetches and merges the "recently-added" personalized shelf for the given libraries. -func (c *Client) GetRecentlyAdded(ctx context.Context, libraries []Library) ([]LibraryItem, error) { - items := make([]LibraryItem, 0) - for _, lib := range libraries { - sections, err := c.GetPersonalized(ctx, lib.ID) - if err != nil { - return nil, fmt.Errorf("get recently added for library %s: %w", lib.ID, err) - } - for _, section := range sections { - if section.ID != "recently-added" { - continue - } - items = append(items, section.Entities...) - break - } - } - SortRecentlyAdded(items) - return items, nil -} - // GetLibraryItems returns a paginated list of items in a library. func (c *Client) GetLibraryItems(ctx context.Context, libraryID string, page, limit int) (*LibraryItemsResponse, error) { return c.getLibraryItems(ctx, libraryID, page, limit, "") @@ -237,65 +206,12 @@ func (c *Client) getLibraryItems(ctx context.Context, libraryID string, page, li return &resp, nil } -const podcastSearchPageLimit = 100 - -// SearchPodcastEpisodes scans podcast library items and returns episode-level prefix hits. -func (c *Client) SearchPodcastEpisodes(ctx context.Context, libraryID, query string) ([]LibraryItem, error) { - normalized := strings.ToLower(strings.TrimSpace(query)) - if normalized == "" { - return nil, nil - } - - page := 0 - items := make([]LibraryItem, 0) - for { - resp, err := c.GetLibraryItems(ctx, libraryID, page, podcastSearchPageLimit) - if err != nil { - return nil, fmt.Errorf("list podcast library items: %w", err) - } - - ids := make([]string, len(resp.Results)) - for i, li := range resp.Results { - ids[i] = li.ID - } - fullItems, err := c.GetLibraryItemsBatch(ctx, ids) - if err != nil { - return nil, err - } - for _, item := range fullItems { - for _, episode := range item.Media.Episodes { - if !strings.HasPrefix(strings.ToLower(episode.Title), normalized) { - continue - } - resultItem := *item - ep := episode - resultItem.RecentEpisode = &ep - resultItem.Media.Episodes = []PodcastEpisode{ep} - items = append(items, resultItem) - } - } - - if len(resp.Results) == 0 || len(resp.Results) < podcastSearchPageLimit { - break - } - loaded := (page + 1) * podcastSearchPageLimit - if resp.Total > 0 && loaded >= resp.Total { - break - } - page++ - } - - return items, nil -} - // GetLibraryItem returns a single library item by ID with full details (including episodes for podcasts). // include=progress makes ABS embed userMediaProgress; expanded=1 is required for include to take effect. func (c *Client) GetLibraryItem(ctx context.Context, itemID string) (*LibraryItem, error) { path := fmt.Sprintf("/api/items/%s?expanded=1&include=progress", itemID) - logger.Debug("API request", "method", "GET", "path", path) data, err := c.do(ctx, http.MethodGet, path, nil) if err != nil { - logger.Error("get library item failed", "itemID", itemID, "err", err) return nil, fmt.Errorf("get library item: %w", err) } @@ -331,6 +247,7 @@ func (c *Client) GetLibraryItemsBatch(ctx context.Context, ids []string) ([]*Lib case sem <- struct{}{}: defer func() { <-sem }() case <-ctx.Done(): + errOnce.Do(func() { firstErr = fmt.Errorf("expand item %s: %w", id, ctx.Err()) }) return } item, err := c.GetLibraryItem(ctx, id) @@ -375,9 +292,6 @@ func (c *Client) GetSeriesContents(ctx context.Context, libraryID, seriesID stri if err != nil { return nil, err } - if series == nil { - return nil, nil - } items := make([]LibraryItem, 0) for page := 0; ; page++ { @@ -387,7 +301,7 @@ func (c *Client) GetSeriesContents(ctx context.Context, libraryID, seriesID stri } items = append(items, resp.Results...) - if len(resp.Results) == 0 || len(resp.Results) < seriesPageLimit { + if len(resp.Results) < seriesPageLimit { break } loaded := (page + 1) * seriesPageLimit @@ -399,10 +313,10 @@ func (c *Client) GetSeriesContents(ctx context.Context, libraryID, seriesID stri // The items list endpoint never includes user progress (ABS merges it // client-side from /api/me), so merge it here. Best-effort: progress is // decorative for the series view and must not fail the whole load. - if me, err := c.GetMe(ctx); err == nil && me != nil { - mergeMediaProgress(items, me.MediaProgress) - } else if err != nil { + if me, err := c.GetMe(ctx); err != nil { logger.Debug("series progress merge skipped", "seriesID", seriesID, "err", err) + } else { + mergeMediaProgress(items, me.MediaProgress) } sortSeriesItems(items, seriesID) @@ -492,10 +406,11 @@ const audioCheckSampleSize = 10 // FilterAudioLibraries filters out "book" type libraries that contain no audio content // (ebooks without audio). Podcasts are always kept. For book libraries, it samples // items and checks if any has Duration > 0 to determine if it's an audio library. -// Audio checks for book libraries run in parallel. -func (c *Client) FilterAudioLibraries(ctx context.Context, libs []Library) ([]Library, error) { +// Audio checks for book libraries run in parallel. A failed check goes to the log, +// and the library is kept. +func (c *Client) FilterAudioLibraries(ctx context.Context, libs []Library) []Library { if len(libs) == 0 { - return libs, nil + return libs } logger.Debug("filtering audio libraries", "inputCount", len(libs)) @@ -545,7 +460,7 @@ func (c *Client) FilterAudioLibraries(ctx context.Context, libs []Library) ([]Li } logger.Info("audio libraries filtered", "inputCount", len(libs), "outputCount", len(result)) - return result, nil + return result } // libraryHasAudio checks if a "book" type library contains any audio items diff --git a/internal/abs/libraries_test.go b/internal/abs/libraries_test.go index 95063f1..505335d 100644 --- a/internal/abs/libraries_test.go +++ b/internal/abs/libraries_test.go @@ -5,8 +5,11 @@ import ( _ "embed" "encoding/base64" "encoding/json" + "errors" "net/http" "net/http/httptest" + "strconv" + "strings" "testing" ) @@ -516,184 +519,6 @@ func TestGetSeriesContentsHTTP(t *testing.T) { } } -func TestGetRecentlyAddedHTTP(t *testing.T) { - responses := map[string]string{ - "/api/libraries/lib-books-001/personalized": `[ - { - "id": "recently-added", - "entities": [ - { - "id": "li-book-001", - "libraryId": "lib-books-001", - "addedAt": 1711111111111, - "mediaType": "book", - "media": {"metadata": {"title": "Caliban's War"}} - } - ] - } - ]`, - "/api/libraries/lib-pods-002/personalized": `[ - { - "id": "recently-added", - "entities": [ - { - "id": "li-pod-001", - "libraryId": "lib-pods-002", - "addedAt": 1712222222222, - "mediaType": "podcast", - "media": {"metadata": {"title": "My Podcast"}} - } - ] - } - ]`, - } - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, ok := responses[r.URL.Path] - if !ok { - t.Fatalf("unexpected path %q", r.URL.Path) - } - if r.Method != http.MethodGet { - t.Errorf("method = %q, want GET", r.Method) - } - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(body)) - })) - defer srv.Close() - - c := NewClient(srv.URL, "tok") - items, err := c.GetRecentlyAdded(context.Background(), []Library{ - {ID: "lib-books-001", MediaType: "book"}, - {ID: "lib-pods-002", MediaType: "podcast"}, - }) - if err != nil { - t.Fatalf("GetRecentlyAdded() error: %v", err) - } - if len(items) != 2 { - t.Fatalf("expected 2 items, got %d", len(items)) - } - if items[0].ID != "li-pod-001" { - t.Errorf("items[0].ID = %q, want li-pod-001", items[0].ID) - } - if items[1].ID != "li-book-001" { - t.Errorf("items[1].ID = %q, want li-book-001", items[1].ID) - } -} - -func TestSearchPodcastEpisodesHTTP(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/api/libraries/lib-pod/items": - if r.URL.Query().Get("page") != "0" { - t.Errorf("page = %q, want 0", r.URL.Query().Get("page")) - } - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{ - "results": [ - { - "id": "pod-001", - "libraryId": "lib-pod", - "mediaType": "podcast", - "media": {"metadata": {"title": "Joe Rogan"}} - } - ], - "total": 1, - "limit": 100, - "page": 0 - }`)) - case "/api/libraries/lib-pod/search": - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"book":[],"podcast":[]}`)) - case "/api/items/pod-001": - if r.URL.Query().Get("expanded") != "1" { - t.Error("expected expanded=1 query param") - } - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{ - "id": "pod-001", - "libraryId": "lib-pod", - "mediaType": "podcast", - "media": { - "metadata": {"title": "Joe Rogan"}, - "episodes": [ - {"id": "ep-001", "title": "Joe Rogan Experience #1", "duration": 3600}, - {"id": "ep-002", "title": "Another Show", "duration": 1800}, - {"id": "ep-003", "title": "Joe Rogan Experience #2", "duration": 4200} - ] - } - }`)) - default: - t.Fatalf("unexpected path %q", r.URL.Path) - } - })) - defer srv.Close() - - c := NewClient(srv.URL, "tok") - items, err := c.SearchPodcastEpisodes(context.Background(), "lib-pod", "Joe Rogan") - if err != nil { - t.Fatalf("SearchPodcastEpisodes() error: %v", err) - } - if len(items) != 2 { - t.Fatalf("expected 2 matching episode hits, got %d", len(items)) - } - if items[0].RecentEpisode == nil || items[0].RecentEpisode.ID != "ep-001" { - t.Fatalf("expected first hit to expose episode ep-001, got %#v", items[0].RecentEpisode) - } - if items[1].RecentEpisode == nil || items[1].RecentEpisode.ID != "ep-003" { - t.Fatalf("expected second hit to expose episode ep-003, got %#v", items[1].RecentEpisode) - } -} - -func TestSearchPodcastEpisodesHTTP_FindsEpisodeWhenShowSearchWouldMiss(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/api/libraries/lib-pod/items": - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{ - "results": [ - { - "id": "pod-001", - "libraryId": "lib-pod", - "mediaType": "podcast", - "media": {"metadata": {"title": "Joe Rogan"}} - } - ], - "total": 1, - "limit": 100, - "page": 0 - }`)) - case "/api/items/pod-001": - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{ - "id": "pod-001", - "libraryId": "lib-pod", - "mediaType": "podcast", - "media": { - "metadata": {"title": "Joe Rogan"}, - "episodes": [ - {"id": "ep-001", "title": "Jason...", "duration": 3600} - ] - } - }`)) - default: - t.Fatalf("unexpected path %q", r.URL.Path) - } - })) - defer srv.Close() - - c := NewClient(srv.URL, "tok") - items, err := c.SearchPodcastEpisodes(context.Background(), "lib-pod", "Jas") - if err != nil { - t.Fatalf("SearchPodcastEpisodes() error: %v", err) - } - if len(items) != 1 { - t.Fatalf("expected 1 matching episode hit, got %d", len(items)) - } - if items[0].RecentEpisode == nil || items[0].RecentEpisode.Title != "Jason..." { - t.Fatalf("expected Jason episode hit, got %#v", items[0].RecentEpisode) - } -} - func TestSortSeriesItems_MultipleSeriesInSeriesList(t *testing.T) { // Each item belongs to two series (s1, s2) with independent sequences. // SeriesByID must select the sequence for the requested series rather than @@ -841,3 +666,66 @@ func TestGetRecentEpisodesHTTP(t *testing.T) { t.Errorf("AuthorName = %v, want empty string", item2.Media.Metadata.AuthorName) } } + +func TestGetLibraryItemsBatchKeepsTheOrderOfTheIDs(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + id := strings.TrimPrefix(r.URL.Path, "/api/items/") + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id": "` + id + `", "mediaType": "podcast"}`)) + })) + defer srv.Close() + + ids := make([]string, 2*batchFetchConcurrency+1) + for i := range ids { + ids[i] = "item-" + strconv.Itoa(i) + } + c := NewClient(srv.URL, "tok") + items, err := c.GetLibraryItemsBatch(context.Background(), ids) + if err != nil { + t.Fatalf("GetLibraryItemsBatch() error: %v", err) + } + if len(items) != len(ids) { + t.Fatalf("GetLibraryItemsBatch() gave %d items, want %d", len(items), len(ids)) + } + for i, item := range items { + if item == nil || item.ID != ids[i] { + t.Fatalf("items[%d] = %+v, want the item %q", i, item, ids[i]) + } + } +} + +func TestGetLibraryItemsBatchReturnsTheErrorOfOneItem(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/items/bad" { + w.WriteHeader(http.StatusInternalServerError) + return + } + _, _ = w.Write([]byte(`{"id": "ok"}`)) + })) + defer srv.Close() + + c := NewClient(srv.URL, "tok") + items, err := c.GetLibraryItemsBatch(context.Background(), []string{"ok", "bad", "ok"}) + if !IsHTTPStatus(err, http.StatusInternalServerError) { + t.Fatalf("GetLibraryItemsBatch() = %v, %v; want the error of the status 500", items, err) + } +} + +func TestGetLibraryItemsBatchWithACanceledContextReturnsAnError(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"id": "a"}`)) + })) + defer srv.Close() + + c := NewClient(srv.URL, "tok") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + // A goroutine of the batch can take a slot or see the canceled context + // first. Each run must return an error. + for range 50 { + items, err := c.GetLibraryItemsBatch(ctx, []string{"a"}) + if !errors.Is(err, context.Canceled) { + t.Fatalf("GetLibraryItemsBatch() = %v, %v; want context.Canceled", items, err) + } + } +} diff --git a/internal/abs/media_test.go b/internal/abs/media_test.go index b9dd7a3..ed84f72 100644 --- a/internal/abs/media_test.go +++ b/internal/abs/media_test.go @@ -151,9 +151,6 @@ func TestMediaMetadataUnmarshalSeriesObject(t *testing.T) { if len(meta.SeriesList) != 1 { t.Fatalf("len(SeriesList) = %d, want 1", len(meta.SeriesList)) } - if got := meta.PrimarySeries(); got == nil || got.ID != "s1" { - t.Fatalf("PrimarySeries() = %+v, want s1", got) - } } func TestMediaMetadataUnmarshalSeriesArray(t *testing.T) { diff --git a/internal/abs/playback.go b/internal/abs/playback.go index 71afa7d..a22f16e 100644 --- a/internal/abs/playback.go +++ b/internal/abs/playback.go @@ -36,44 +36,40 @@ type syncSessionRequest struct { // StartPlaySession starts a new playback session for a library item. func (c *Client) StartPlaySession(ctx context.Context, itemID string, device DeviceInfo) (*PlaySession, error) { path := fmt.Sprintf("/api/items/%s/play", itemID) - logger.Debug("API request", "method", "POST", "path", path, "itemID", itemID) body := startPlayRequest{ DeviceInfo: device, ForceDirectPlay: true, } data, err := c.do(ctx, http.MethodPost, path, body) if err != nil { - logger.Error("start play session failed", "itemID", itemID, "err", err) return nil, fmt.Errorf("start play session: %w", err) } var session PlaySession if err := json.Unmarshal(data, &session); err != nil { - logger.Error("decode play session failed", "itemID", itemID, "err", err, "body", string(data)) + logger.Error("decode play session failed", "itemID", itemID, "err", err, "bodyLen", len(data)) return nil, fmt.Errorf("decode play session: %w", err) } - logger.Info("play session created", "sessionID", session.ID, "tracks", len(session.AudioTracks), "chapters", len(session.Chapters), "mediaMetadataChapters", len(session.MediaMetadata.Chapters), "currentTime", session.CurrentTime) + logger.Info("play session created", "session", SessionTag(session.ID), "tracks", len(session.AudioTracks), "chapters", len(session.Chapters), "mediaMetadataChapters", len(session.MediaMetadata.Chapters), "currentTime", session.CurrentTime) return &session, nil } // StartEpisodePlaySession starts a new playback session for a podcast episode. func (c *Client) StartEpisodePlaySession(ctx context.Context, itemID, episodeID string, device DeviceInfo) (*PlaySession, error) { path := fmt.Sprintf("/api/items/%s/play/%s", itemID, episodeID) - logger.Debug("API request", "method", "POST", "path", path, "itemID", itemID, "episodeID", episodeID) body := startPlayRequest{ DeviceInfo: device, ForceDirectPlay: true, } data, err := c.do(ctx, http.MethodPost, path, body) if err != nil { - logger.Error("start episode play session failed", "itemID", itemID, "episodeID", episodeID, "err", err) return nil, fmt.Errorf("start episode play session: %w", err) } var session PlaySession if err := json.Unmarshal(data, &session); err != nil { - logger.Error("decode episode play session failed", "itemID", itemID, "episodeID", episodeID, "err", err, "body", string(data)) + logger.Error("decode episode play session failed", "itemID", itemID, "episodeID", episodeID, "err", err, "bodyLen", len(data)) return nil, fmt.Errorf("decode episode play session: %w", err) } - logger.Info("episode play session created", "sessionID", session.ID, "tracks", len(session.AudioTracks), "chapters", len(session.Chapters), "mediaMetadataChapters", len(session.MediaMetadata.Chapters), "currentTime", session.CurrentTime, "episodeID", session.EpisodeID) + logger.Info("episode play session created", "session", SessionTag(session.ID), "tracks", len(session.AudioTracks), "chapters", len(session.Chapters), "mediaMetadataChapters", len(session.MediaMetadata.Chapters), "currentTime", session.CurrentTime, "episodeID", session.EpisodeID) return &session, nil } @@ -84,7 +80,7 @@ func (c *Client) SyncSession(ctx context.Context, sessionID string, currentTime, CurrentTime: currentTime, TimeListened: timeListened, } - logger.Debug("syncing playback session", "sessionID", sessionID, "currentTime", currentTime, "timeListened", timeListened) + logger.Debug("syncing playback session", "session", SessionTag(sessionID), "currentTime", currentTime, "timeListened", timeListened) _, err := c.do(ctx, http.MethodPost, path, body) if err != nil { return fmt.Errorf("sync session: %w", err) @@ -100,7 +96,7 @@ func (c *Client) CloseSession(ctx context.Context, sessionID string, currentTime CurrentTime: currentTime, TimeListened: timeListened, } - logger.Debug("closing playback session", "sessionID", sessionID, "currentTime", currentTime, "timeListened", timeListened) + logger.Debug("closing playback session", "session", SessionTag(sessionID), "currentTime", currentTime, "timeListened", timeListened) _, err := c.do(ctx, http.MethodPost, path, body) if err != nil { return fmt.Errorf("close session: %w", err) @@ -112,7 +108,7 @@ func (c *Client) CloseSession(ctx context.Context, sessionID string, currentTime // so the server keeps the progress that it has. func (c *Client) CloseSessionNoSync(ctx context.Context, sessionID string) error { path := fmt.Sprintf("/api/session/%s/close", sessionID) - logger.Debug("closing playback session with no sync", "sessionID", sessionID) + logger.Debug("closing playback session with no sync", "session", SessionTag(sessionID)) _, err := c.do(ctx, http.MethodPost, path, nil) if err != nil { return fmt.Errorf("close session: %w", err) diff --git a/internal/abs/playback_test.go b/internal/abs/playback_test.go index 39b17a5..1ccdfa1 100644 --- a/internal/abs/playback_test.go +++ b/internal/abs/playback_test.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "net/http/httptest" + "strings" "testing" ) @@ -270,3 +271,52 @@ func TestCloseSessionNoSyncHTTP(t *testing.T) { t.Errorf("body = %q, want no body", capturedBody) } } + +func TestSyncSessionErrorHasNoSessionID(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + addr := srv.URL + srv.Close() + + const sessionID = "3f2b8c1e-5d4a-4e7b-9a6c-1d2e3f4a5b6c" + c := NewClient(addr, "tok") + err := c.SyncSession(context.Background(), sessionID, 10, 5) + if err == nil { + t.Fatal("SyncSession() to a closed server returned no error") + } + if strings.Contains(err.Error(), sessionID) { + t.Errorf("SyncSession() error %q contains the session ID", err) + } + if !strings.Contains(err.Error(), "/api/session/"+SessionTag(sessionID)+"/sync") { + t.Errorf("SyncSession() error %q does not name the session tag", err) + } +} + +func TestSessionTagHidesTheSessionID(t *testing.T) { + const id = "3f2b8c1e-5d4a-4e7b-9a6c-1d2e3f4a5b6c" + tag := SessionTag(id) + if strings.Contains(tag, id[:6]) || len(tag) > 8 { + t.Errorf("SessionTag(%q) = %q, want a short tag that does not show the ID", id, tag) + } + if SessionTag(id) != tag { + t.Errorf("SessionTag(%q) gave two tags", id) + } + if SessionTag("other-session") == tag { + t.Errorf("SessionTag gave the same tag %q for two IDs", tag) + } +} + +func TestLogPathPutsTheSessionTagInPlaceOfTheID(t *testing.T) { + tests := []struct { + path, want string + }{ + {"/api/session/abc/sync", "/api/session/" + SessionTag("abc") + "/sync"}, + {"/api/session/abc/close", "/api/session/" + SessionTag("abc") + "/close"}, + {"/api/session/abc", "/api/session/" + SessionTag("abc")}, + {"/api/items/abc/play", "/api/items/abc/play"}, + } + for _, tt := range tests { + if got := logPath(tt.path); got != tt.want { + t.Errorf("logPath(%q) = %q, want %q", tt.path, got, tt.want) + } + } +} diff --git a/internal/abs/progress.go b/internal/abs/progress.go index aa85577..63a0a23 100644 --- a/internal/abs/progress.go +++ b/internal/abs/progress.go @@ -17,15 +17,25 @@ type updateProgressRequest struct { IsFinished *bool `json:"isFinished,omitempty"` } -// UpdateProgress updates the user's progress on a library item. -func (c *Client) UpdateProgress(ctx context.Context, itemID string, currentTime, progress float64, isFinished bool) error { - path := fmt.Sprintf("/api/me/progress/%s", itemID) +// progressPath is the path of the progress of a library item, or of a +// podcast episode if episodeID is not empty. +func progressPath(itemID, episodeID string) string { + path := "/api/me/progress/" + itemID + if episodeID != "" { + path += "/" + episodeID + } + return path +} + +// UpdateProgress updates the user's progress on a library item, or on a +// podcast episode if episodeID is not empty. +func (c *Client) UpdateProgress(ctx context.Context, itemID, episodeID string, currentTime, progress float64, isFinished bool) error { body := updateProgressRequest{ CurrentTime: currentTime, Progress: progress, IsFinished: &isFinished, } - _, err := c.do(ctx, http.MethodPatch, path, body) + _, err := c.do(ctx, http.MethodPatch, progressPath(itemID, episodeID), body) if err != nil { return fmt.Errorf("update progress: %w", err) } @@ -35,15 +45,11 @@ func (c *Client) UpdateProgress(ctx context.Context, itemID string, currentTime, // UpdatePosition updates the user's position in a library item, or in a // podcast episode if episodeID is not empty. It sends no isFinished key. func (c *Client) UpdatePosition(ctx context.Context, itemID, episodeID string, currentTime, progress float64) error { - path := fmt.Sprintf("/api/me/progress/%s", itemID) - if episodeID != "" { - path += "/" + episodeID - } body := updateProgressRequest{ CurrentTime: currentTime, Progress: progress, } - _, err := c.do(ctx, http.MethodPatch, path, body) + _, err := c.do(ctx, http.MethodPatch, progressPath(itemID, episodeID), body) if err != nil { return fmt.Errorf("update position: %w", err) } @@ -64,18 +70,3 @@ func (c *Client) GetMediaProgress(ctx context.Context, itemID string) (*MediaPro } return &progress, nil } - -// UpdateEpisodeProgress updates the user's progress on a podcast episode. -func (c *Client) UpdateEpisodeProgress(ctx context.Context, itemID, episodeID string, currentTime, progress float64, isFinished bool) error { - path := fmt.Sprintf("/api/me/progress/%s/%s", itemID, episodeID) - body := updateProgressRequest{ - CurrentTime: currentTime, - Progress: progress, - IsFinished: &isFinished, - } - _, err := c.do(ctx, http.MethodPatch, path, body) - if err != nil { - return fmt.Errorf("update episode progress: %w", err) - } - return nil -} diff --git a/internal/abs/progress_test.go b/internal/abs/progress_test.go index fbc6c05..84dadf9 100644 --- a/internal/abs/progress_test.go +++ b/internal/abs/progress_test.go @@ -25,7 +25,7 @@ func TestUpdateProgressHTTP(t *testing.T) { defer srv.Close() c := NewClient(srv.URL, "tok") - err := c.UpdateProgress(context.Background(), "li-001", 500.5, 0.45, false) + err := c.UpdateProgress(context.Background(), "li-001", "", 500.5, 0.45, false) if err != nil { t.Fatalf("UpdateProgress() error: %v", err) } @@ -58,7 +58,7 @@ func TestUpdateProgressFinishedHTTP(t *testing.T) { defer srv.Close() c := NewClient(srv.URL, "tok") - err := c.UpdateProgress(context.Background(), "li-002", 3600.0, 1.0, true) + err := c.UpdateProgress(context.Background(), "li-002", "", 3600.0, 1.0, true) if err != nil { t.Fatalf("UpdateProgress() error: %v", err) } @@ -173,7 +173,7 @@ func TestGetMediaProgressNotFoundReturnsError(t *testing.T) { } } -func TestUpdateEpisodeProgressHTTP(t *testing.T) { +func TestUpdateProgressOfEpisodeHTTP(t *testing.T) { var capturedBody []byte srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/api/me/progress/li-pod-001/ep-001" { @@ -188,9 +188,9 @@ func TestUpdateEpisodeProgressHTTP(t *testing.T) { defer srv.Close() c := NewClient(srv.URL, "tok") - err := c.UpdateEpisodeProgress(context.Background(), "li-pod-001", "ep-001", 300.0, 0.5, false) + err := c.UpdateProgress(context.Background(), "li-pod-001", "ep-001", 300.0, 0.5, false) if err != nil { - t.Fatalf("UpdateEpisodeProgress() error: %v", err) + t.Fatalf("UpdateProgress() error: %v", err) } var body struct { diff --git a/internal/abs/types.go b/internal/abs/types.go index 29f7e66..4bc9daf 100644 --- a/internal/abs/types.go +++ b/internal/abs/types.go @@ -1,9 +1,7 @@ package abs import ( - "cmp" "encoding/json" - "slices" "strings" ) @@ -50,16 +48,6 @@ type FileMetadata struct { Ext string `json:"ext,omitempty"` } -// SortRecentlyAdded sorts library items by descending addedAt and then title. -func SortRecentlyAdded(items []LibraryItem) { - slices.SortFunc(items, func(a, b LibraryItem) int { - if byAddedAt := cmp.Compare(b.AddedAt, a.AddedAt); byAddedAt != 0 { - return byAddedAt - } - return cmp.Compare(a.Media.Metadata.Title, b.Media.Metadata.Title) - }) -} - // Media contains the media content and metadata of a library item. type Media struct { Metadata MediaMetadata `json:"metadata"` @@ -195,14 +183,6 @@ func (m MediaMetadata) DisplayAuthor() string { return "Unknown author" } -// PrimarySeries returns the first ABS series entry used by pine's current single-series behavior. -func (m MediaMetadata) PrimarySeries() *SeriesSequence { - if len(m.SeriesList) > 0 { - return &m.SeriesList[0] - } - return m.Series -} - // HasMultipleAuthors reports whether ABS returned more than one non-empty author. func (m MediaMetadata) HasMultipleAuthors() bool { count := 0 @@ -245,21 +225,14 @@ type SeriesSequence struct { Sequence string `json:"sequence,omitempty"` } -// SeriesBook is a library item embedded in some ABS responses with sequence info. -type SeriesBook struct { - LibraryItem - Sequence string `json:"sequence,omitempty"` -} - // Series contains series metadata returned by ABS. type Series struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description,omitempty"` - LibraryID string `json:"libraryId,omitempty"` - AddedAt int64 `json:"addedAt,omitempty"` - UpdatedAt int64 `json:"updatedAt,omitempty"` - Books []SeriesBook `json:"books"` + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + LibraryID string `json:"libraryId,omitempty"` + AddedAt int64 `json:"addedAt,omitempty"` + UpdatedAt int64 `json:"updatedAt,omitempty"` } // SeriesContents combines series metadata with the library items in that series. diff --git a/internal/app/bookmarks.go b/internal/app/bookmarks.go index 7cf1ced..570b9c0 100644 --- a/internal/app/bookmarks.go +++ b/internal/app/bookmarks.go @@ -281,24 +281,26 @@ func (m Model) seekToChapter(target float64, ok bool) (Model, tea.Cmd) { // seekToBookGlobalPosition seeks to a book-global position. If the position // falls within the current track, seeks mpv directly. Otherwise stops playback -// and starts a new session so ABS picks the correct track. +// and starts a new session so ABS picks the correct track. An episode has one +// track, so a seek in an episode always seeks mpv. func (m Model) seekToBookGlobalPosition(bookPos float64) (Model, tea.Cmd) { trackDur := m.trackDuration if trackDur == 0 { trackDur = m.player.Duration } trackEnd := m.trackStartOffset + trackDur - if bookPos >= m.trackStartOffset && bookPos < trackEnd { + if m.episodeID != "" || (bookPos >= m.trackStartOffset && bookPos < trackEnd) { trackRelative := bookPos - m.trackStartOffset logger.Debug("in-track seek", "bookPosition", bookPos, "trackStart", m.trackStartOffset, "trackEnd", trackEnd, "trackRelative", trackRelative) m.player.Position = bookPos m.seekPending = true m.seekPendingSince = time.Now() + m.syncMprisState() mpvPlayer := m.mpv - return m, func() tea.Msg { + return m, tea.Batch(func() tea.Msg { _ = mpvPlayer.Seek(trackRelative) return nil - } + }, m.mprisSeekedCmd()) } // Cross-track seek: restart playback at the new book-global position. diff --git a/internal/app/e2e_test.go b/internal/app/e2e_test.go index 0b84395..b496a1a 100644 --- a/internal/app/e2e_test.go +++ b/internal/app/e2e_test.go @@ -1,10 +1,12 @@ package app import ( + "context" "fmt" "net/http" "strings" "testing" + "time" "github.com/Thelost77/pine/internal/abs" "github.com/Thelost77/pine/internal/cache" @@ -15,6 +17,7 @@ import ( "github.com/Thelost77/pine/internal/screens/home" "github.com/Thelost77/pine/internal/screens/library" "github.com/Thelost77/pine/internal/screens/login" + "github.com/Thelost77/pine/internal/screens/metadataedit" "github.com/Thelost77/pine/internal/ui/components" tea "github.com/charmbracelet/bubbletea" ) @@ -264,7 +267,7 @@ func TestE2E_DetailToPlayback(t *testing.T) { assertViewContains(t, m, "The Great Gatsby") // Trigger sync - res, cmd := m.Update(SyncTickMsg{}) + res, cmd := m.Update(SyncTickMsg{Generation: m.playGeneration}) m = res.(Model) executeBatchCmds(cmd) @@ -1101,7 +1104,7 @@ func TestE2E_401Redirect(t *testing.T) { assertScreen(t, m, ScreenHome) // Simulate a 401 error - res, _ := m.Update(components.ErrMsg{Err: fmt.Errorf("unexpected status 401: unauthorized")}) + res, _ := m.Update(components.ErrMsg{Err: &abs.HTTPStatusError{StatusCode: http.StatusUnauthorized}}) m = res.(Model) // Should redirect to login @@ -1431,7 +1434,7 @@ func TestE2E_FullJourney(t *testing.T) { assertAPICallMade(t, log, "POST", "/api/me/item/") // === Phase 8: Sync tick === - res, cmd := m.Update(SyncTickMsg{}) + res, cmd := m.Update(SyncTickMsg{Generation: m.playGeneration}) m = res.(Model) executeBatchCmds(cmd) assertAPICallMade(t, log, "POST", "/api/session/sess-e2e/sync") @@ -2327,11 +2330,8 @@ func TestE2E_SessionRestore(t *testing.T) { // Save a session to the DB simulating a previous listening session if err := store.SaveListeningSession(db.ListeningSession{ - ItemID: "item-001", - EpisodeID: "", - SessionID: "sess-old", - CurrentTime: 100.0, - Duration: 3600.0, + ItemID: "item-001", + EpisodeID: "", }); err != nil { t.Fatalf("SaveListeningSession: %v", err) } @@ -2373,11 +2373,8 @@ func TestE2E_SessionRestorePodcastMissingEpisodeSkipsSilently(t *testing.T) { m = e2eSetSize(m, 120, 40) if err := store.SaveListeningSession(db.ListeningSession{ - ItemID: "pod-001", - EpisodeID: "pod-001-ep-missing", - SessionID: "sess-old-pod", - CurrentTime: 100.0, - Duration: 1800.0, + ItemID: "pod-001", + EpisodeID: "pod-001-ep-missing", }); err != nil { t.Fatalf("SaveListeningSession: %v", err) } @@ -2418,11 +2415,8 @@ func TestE2E_SessionRestorePodcastNoTracksSkipsSilently(t *testing.T) { m = e2eSetSize(m, 120, 40) if err := store.SaveListeningSession(db.ListeningSession{ - ItemID: "pod-001", - EpisodeID: "pod-001-ep-001", - SessionID: "sess-old-pod", - CurrentTime: 100.0, - Duration: 1800.0, + ItemID: "pod-001", + EpisodeID: "pod-001-ep-001", }); err != nil { t.Fatalf("SaveListeningSession: %v", err) } @@ -2518,3 +2512,141 @@ func TestE2E_CacheSurvivesRestart(t *testing.T) { t.Fatalf("expected cache hit on restart, but API was called again: before=%d after=%d", personalizedCallsBefore, personalizedCallsAfter) } } + +// TestE2E_PaletteSearchResultsPlayWithP verifies that pine gives each search +// result of the command palette the play action of the key p. +func TestE2E_PaletteSearchResultsPlayWithP(t *testing.T) { + log := &apiLog{} + state := &e2eServerState{bookmarks: make(map[string][]abs.Bookmark)} + srv := newFullMockABSServer(log, state) + defer srv.Close() + + m := newE2EModelAuthenticated(srv, &mockPlayer{}) + m = e2eSetSize(m, 120, 40) + cmd := m.home.Init() + m, cmd = feedCmd(m, cmd) + m = feedCmdChain(m, cmd, 5) + // The search answers only from a snapshot that is built. + m, _ = feedCmdWithin(m, m.prewarmCacheCmd(), slowCmdWait) + + results := m.contentSearchFunc()("gatsby") + if len(results) == 0 { + t.Fatal("the search found no item") + } + for _, item := range results { + if item.PlayAction != components.ActionPlayDirect { + t.Errorf("search result %q has the play action %v, want ActionPlayDirect", item.Label, item.PlayAction) + } + } +} + +// TestE2E_PaletteShowsResultsWhenSnapshotIsBuilt verifies that the palette +// shows the results of its query when the search snapshot is built while the +// palette is open. The search does not wait for the build. +func TestE2E_PaletteShowsResultsWhenSnapshotIsBuilt(t *testing.T) { + log := &apiLog{} + state := &e2eServerState{bookmarks: make(map[string][]abs.Bookmark)} + srv := newFullMockABSServer(log, state) + defer srv.Close() + + m := newE2EModelAuthenticated(srv, &mockPlayer{}) + m = e2eSetSize(m, 120, 40) + m, cmd := feedCmd(m, m.home.Init()) + m = feedCmdChain(m, cmd, 5) + // No snapshot is ready, for example after the TTL of the snapshot. + m.searchCache.Invalidate("lib-001") + + res, openCmd := m.Update(tea.KeyMsg{Type: tea.KeyCtrlP}) + m = res.(Model) + res, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("gatsby")}) + m = res.(Model) + if strings.Contains(m.palette.View(), "The Great Gatsby") { + t.Fatal("the palette shows a result before the snapshot is built") + } + if err := m.searchCache.Prepare(context.Background(), "lib-001", "book"); err != nil { + t.Fatalf("Prepare() error: %v", err) + } + m, _ = feedCmdWithin(m, openCmd, slowCmdWait) + + if !strings.Contains(m.palette.View(), "The Great Gatsby") { + t.Error("the palette shows no result after the snapshot is built") + } +} + +// TestE2E_MetadataSaveBuildsSearchSnapshot verifies that a metadata save +// builds the search snapshot again: the save clears the snapshots. +func TestE2E_MetadataSaveBuildsSearchSnapshot(t *testing.T) { + log := &apiLog{} + state := &e2eServerState{bookmarks: make(map[string][]abs.Bookmark)} + srv := newFullMockABSServer(log, state) + defer srv.Close() + + m := newE2EModelAuthenticated(srv, &mockPlayer{}) + m, cmd := feedCmd(m, m.home.Init()) + m = feedCmdChain(m, cmd, 5) + // The save clears the caches before Update gets SavedMsg. + m.client.OnInvalidate() + + item := testLibraryItem("item-001", "The Great Gatsby") + res, cmd := m.Update(metadataedit.SavedMsg{ItemID: item.ID, Item: &item}) + m = res.(Model) + _, _ = feedCmdWithin(m, cmd, slowCmdWait) + + if _, ok := m.searchCache.TryGetAll("lib-001", "book"); !ok { + t.Error("no search snapshot after the metadata save") + } +} + +// TestE2E_LoginGivesLibraryTheSearchCacheOfTheLogin verifies that the library +// screen reads the search cache that the login makes: the prewarm of the +// login builds the snapshots in that cache. +func TestE2E_LoginGivesLibraryTheSearchCacheOfTheLogin(t *testing.T) { + log := &apiLog{} + state := &e2eServerState{bookmarks: make(map[string][]abs.Bookmark)} + srv := newFullMockABSServer(log, state) + defer srv.Close() + + m := newE2EModel(srv, &mockPlayer{}) + res, _ := m.Update(login.LoginSuccessMsg{Token: "jwt-token-e2e", ServerURL: srv.URL, Username: "alice"}) + m = res.(Model) + if err := m.searchCache.Prepare(context.Background(), "lib-001", "book"); err != nil { + t.Fatalf("Prepare() error: %v", err) + } + + m.library.Configure("lib-001", []abs.Library{{ID: "lib-001", Name: "Audiobooks", MediaType: "book"}}) + if m.library.Loading() || len(m.library.Items()) == 0 { + t.Error("the library does not read the snapshot of the search cache of the login") + } +} + +// TestE2E_LoginClearsCacheStore verifies that a login clears the persistent +// cache: its keys have no account, so the data of the account of an earlier +// login must not reach the new account. +func TestE2E_LoginClearsCacheStore(t *testing.T) { + log := &apiLog{} + state := &e2eServerState{bookmarks: make(map[string][]abs.Bookmark)} + srv := newFullMockABSServer(log, state) + defer srv.Close() + + store, err := db.Open(t.TempDir() + "/test.db") + if err != nil { + t.Fatalf("failed to open test db: %v", err) + } + defer func() { _ = store.Close() }() + cacheStore := cache.NewStore(store) + if err := cacheStore.Put(cache.ItemKey("item-old-account"), abs.LibraryItem{ID: "item-old-account"}, time.Hour); err != nil { + t.Fatalf("Put() error: %v", err) + } + + m := NewWithPlayer(config.Default(), store, nil, cacheStore, &mockPlayer{}) + res, _ := m.Update(login.LoginSuccessMsg{Token: "jwt-token-e2e", ServerURL: srv.URL, Username: "alice"}) + m = res.(Model) + + var item abs.LibraryItem + if hit, err := cacheStore.Get(cache.ItemKey("item-old-account"), &item); err != nil || hit { + t.Errorf("Get() = %v, %v after the login, want a miss", hit, err) + } + if m.client == nil { + t.Error("the login sets no client") + } +} diff --git a/internal/app/messages.go b/internal/app/messages.go index ae76912..60640ec 100644 --- a/internal/app/messages.go +++ b/internal/app/messages.go @@ -74,6 +74,7 @@ type PlaySessionData struct { TrackDuration float64 TrackFilename string TranscriptIno string + HasLibraryFiles bool // the session gave the files of the item } // QueueEntry represents a queued book or podcast episode. @@ -83,7 +84,10 @@ type QueueEntry struct { } // SyncTickMsg fires every 30 seconds to sync playback progress with ABS. -type SyncTickMsg struct{} +// Generation is the playGeneration of the playback that started the ticks. +type SyncTickMsg struct { + Generation uint64 +} // SessionSyncedMsg carries the result of a sync of the playback session. // NewSessionID is the session that pine opened because the server did not diff --git a/internal/app/metadata.go b/internal/app/metadata.go index ab7194e..58079cd 100644 --- a/internal/app/metadata.go +++ b/internal/app/metadata.go @@ -89,23 +89,24 @@ func (m Model) handleMetadataSaved(msg metadataedit.SavedMsg) (Model, tea.Cmd) { mprisChanged := false if msg.Item != nil { updated := *msg.Item - if m.detail.ItemID() == updated.ID { - m.detail.SetItem(updated) - } + m.setDetailItem(updated) mprisChanged = m.applyMetadataUpdate(updated) } + // The save cleared the search snapshots. Build the snapshot again, as a + // delete does. + prewarmCmd := m.prewarmCacheCmd() if activeEditor { m.metadataEdit, _ = m.metadataEdit.Update(msg) m, backCmd := m.back() if mprisChanged { - return m, tea.Batch(backCmd, m.mprisTitleCmd()) + return m, tea.Batch(backCmd, m.mprisTitleCmd(), prewarmCmd) } - return m, backCmd + return m, tea.Batch(backCmd, prewarmCmd) } if mprisChanged { - return m, m.mprisTitleCmd() + return m, tea.Batch(m.mprisTitleCmd(), prewarmCmd) } - return m, nil + return m, prewarmCmd } func (m Model) handleEpisodeMetadataSaved(msg metadataedit.SavedEpisodeMsg) (Model, tea.Cmd) { @@ -123,33 +124,44 @@ func (m Model) handleEpisodeMetadataSaved(msg metadataedit.SavedEpisodeMsg) (Mod mprisChanged := false if msg.Item != nil { updated := *msg.Item - if m.detail.ItemID() == updated.ID { - m.detail.SetItem(updated) - } + m.setDetailItem(updated) mprisChanged = m.applyMetadataUpdate(updated) mprisChanged = m.applyEpisodeMetadataUpdate(updated, msg.EpisodeID) || mprisChanged } + // The save cleared the search snapshots. Build the snapshot again, as a + // delete does. + prewarmCmd := m.prewarmCacheCmd() if activeEditor { m.metadataEdit, _ = m.metadataEdit.Update(msg) m, backCmd := m.back() if mprisChanged { - return m, tea.Batch(backCmd, m.mprisTitleCmd()) + return m, tea.Batch(backCmd, m.mprisTitleCmd(), prewarmCmd) } - return m, backCmd + return m, tea.Batch(backCmd, prewarmCmd) } if mprisChanged { - return m, m.mprisTitleCmd() + return m, tea.Batch(m.mprisTitleCmd(), prewarmCmd) } - return m, nil + return m, prewarmCmd +} + +// setDetailItem shows updated on the detail screen if the screen shows that +// item. The answer of a metadata save has no progress of the user, so the +// progress on the screen stays. +func (m *Model) setDetailItem(updated abs.LibraryItem) { + if m.detail.ItemID() != updated.ID { + return + } + if updated.UserMediaProgress == nil { + updated.UserMediaProgress = m.detail.Item().UserMediaProgress + } + m.detail.SetItem(updated) } func (m *Model) applyMetadataUpdate(updated abs.LibraryItem) bool { mprisChanged := false m.home.ReplaceItem(updated) m.library.ReplaceItem(updated) - if m.searchCache != nil { - m.searchCache.UpdateItem(updated) - } for i := range m.queue { if m.queue[i].Item.ID == updated.ID { @@ -163,7 +175,7 @@ func (m *Model) applyMetadataUpdate(updated abs.LibraryItem) bool { m.syncMprisState() mprisChanged = true } - if m.lastPlayedItemID == updated.ID && updated.MediaType != "podcast" { + if m.lastPlayedTrackID == updated.ID && updated.MediaType != "podcast" { m.lastPlayedTitle = updated.Media.Metadata.Title m.lastPlayedAuthors = mprisAuthors(updated) m.syncMprisState() diff --git a/internal/app/model.go b/internal/app/model.go index de743ff..725b68b 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "strings" + "net/http" "time" "github.com/Thelost77/pine/internal/abs" @@ -74,34 +74,37 @@ type Model struct { queue []QueueEntry restorePaused bool propertyUnavailableCount int - lastMprisEmit time.Time seekPending bool seekPendingSince time.Time lastEvict time.Time - // Series auto-continue + // playRequested is true after a play request of the user. The restore + // of the last session at the start then does nothing. + playRequested bool + + // The library and the series of the item that plays: for the cache + // eviction after the playback, and for the series auto-continue. playbackLibraryID string playbackSeriesID string - keys KeyMap - err components.ErrorBanner - help components.HelpOverlay - width int - height int - styles ui.Styles - config config.Config - db *db.Store - client *cache.Client - cacheStore *cache.Store - mpv player.Player - mprisBridge *mpris.Bridge - program *tea.Program - mprisState *MprisState + keys KeyMap + err components.ErrorBanner + help components.HelpOverlay + width int + height int + styles ui.Styles + config config.Config + db *db.Store + client *cache.Client + cacheStore *cache.Store + mpv player.Player + mprisLink *mprisLink + mprisState *MprisState palette components.Palette lastPlayedTitle string - lastPlayedItemID string + lastPlayedTrackID string lastPlayedAuthors []string currentAuthors []string @@ -148,6 +151,7 @@ func NewWithPlayer(cfg config.Config, store *db.Store, client *cache.Client, cac client: client, cacheStore: cacheStore, mpv: mpv, + mprisLink: &mprisLink{}, mprisState: &MprisState{}, palette: palette, } @@ -162,15 +166,30 @@ func (m Model) Queue() []QueueEntry { return cp } -// SetProgram sets the bubbletea program reference and starts the MPRIS bridge. +// mprisLink holds the MPRIS bridge. The copies of the model share it, so the +// model that the program runs gets the bridge: main calls SetProgram after +// tea.NewProgram copies the model. +type mprisLink struct { + bridge *mpris.Bridge +} + +// SetProgram starts the MPRIS bridge, which sends the MPRIS requests to p. func (m *Model) SetProgram(p *tea.Program) { - m.program = p - m.mprisBridge = mpris.NewBridge(p, "pine") + bridge := mpris.NewBridge(p, "pine") state := m.mprisState - m.mprisBridge.Bind(func() mpris.ModelAccessor { + bridge.Bind(func() mpris.ModelAccessor { return state }, float64(m.config.Player.SeekSeconds)) - m.mprisBridge.Start() + m.mprisLink.bridge = bridge + bridge.Start() +} + +// mprisBridge returns the MPRIS bridge, or nil before SetProgram. +func (m Model) mprisBridge() *mpris.Bridge { + if m.mprisLink == nil { + return nil + } + return m.mprisLink.bridge } // setMprisPlaying applies an MPRIS request to play or pause the active item. @@ -187,10 +206,11 @@ func (m Model) setMprisPlaying(playing bool) (Model, tea.Cmd) { } func (m *Model) mprisPlaybackCmd() tea.Cmd { - if m.mprisBridge == nil { + bridge := m.mprisBridge() + if bridge == nil { return nil } - server := m.mprisBridge.Server() + server := bridge.Server() return func() tea.Msg { server.PlaybackChanged() return nil @@ -198,10 +218,11 @@ func (m *Model) mprisPlaybackCmd() tea.Cmd { } func (m *Model) mprisPlayPauseCmd() tea.Cmd { - if m.mprisBridge == nil { + bridge := m.mprisBridge() + if bridge == nil { return nil } - server := m.mprisBridge.Server() + server := bridge.Server() return func() tea.Msg { server.StatusChanged() return nil @@ -209,10 +230,11 @@ func (m *Model) mprisPlayPauseCmd() tea.Cmd { } func (m *Model) mprisEndedCmd() tea.Cmd { - if m.mprisBridge == nil { + bridge := m.mprisBridge() + if bridge == nil { return nil } - server := m.mprisBridge.Server() + server := bridge.Server() return func() tea.Msg { server.StatusChanged() return nil @@ -220,26 +242,26 @@ func (m *Model) mprisEndedCmd() tea.Cmd { } func (m *Model) mprisTitleCmd() tea.Cmd { - if m.mprisBridge == nil { + bridge := m.mprisBridge() + if bridge == nil { return nil } - server := m.mprisBridge.Server() + server := bridge.Server() return func() tea.Msg { server.MetadataChanged() return nil } } -func (m *Model) mprisPositionCmd() tea.Cmd { - if m.mprisBridge == nil { - return nil - } - now := time.Now() - if now.Sub(m.lastMprisEmit) < time.Second { +// mprisSeekedCmd tells MPRIS clients the position after a seek. A client +// computes the position of a playback from the rate, so a position tick sends +// no Seeked. +func (m *Model) mprisSeekedCmd() tea.Cmd { + bridge := m.mprisBridge() + if bridge == nil { return nil } - m.lastMprisEmit = now - server := m.mprisBridge.Server() + server := bridge.Server() pos := m.player.Position return func() tea.Msg { server.Seeked(pos) @@ -248,16 +270,26 @@ func (m *Model) mprisPositionCmd() tea.Cmd { } func (m *Model) mprisVolumeCmd() tea.Cmd { - if m.mprisBridge == nil { + bridge := m.mprisBridge() + if bridge == nil { return nil } - server := m.mprisBridge.Server() + server := bridge.Server() return func() tea.Msg { server.VolumeChanged() return nil } } +// mprisTrackID returns the MPRIS track of an item, or of an episode of a +// podcast: each episode is a track of its own. +func mprisTrackID(itemID, episodeID string) string { + if episodeID == "" { + return itemID + } + return itemID + "_" + episodeID +} + func (m *Model) syncMprisState() { authors := m.currentAuthors if m.player.Title == "" { @@ -267,9 +299,9 @@ func (m *Model) syncMprisState() { if title == "" { title = m.lastPlayedTitle } - itemID := m.itemID + itemID := mprisTrackID(m.itemID, m.episodeID) if itemID == "" { - itemID = m.lastPlayedItemID + itemID = m.lastPlayedTrackID } playing := m.isPlaying() m.mprisState.Update(func(s *MprisState) { @@ -331,7 +363,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, cmd case components.ErrorDismissMsg: - m.err.Dismiss() + m.err.HandleDismiss(msg) m.propagateSize() return m, nil @@ -346,6 +378,13 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case login.LoginSuccessMsg: logger.Info("login success", "server", msg.ServerURL, "user", msg.Username) + // The cache keys have no account, so the cached data of an earlier + // account must go. + if m.cacheStore != nil { + if err := m.cacheStore.ClearAll(); err != nil { + logger.Warn("failed to clear the cache at login", "err", err) + } + } absClient := abs.NewClient(msg.ServerURL, msg.Token) m.client = cache.NewClient(absClient, m.cacheStore) if m.db != nil { @@ -355,14 +394,13 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { ServerURL: msg.ServerURL, Username: msg.Username, Token: msg.Token, - IsDefault: true, }); err != nil { logger.Warn("failed to save account", "err", err) } } m.home = home.New(m.styles, m.client) - m.library = library.New(m.styles, m.client, m.searchCache, "", nil) m.searchCache = search.NewCache(m.client, m.cacheStore) + m.library = library.New(m.styles, m.client, m.searchCache, "", nil) m.metadataEdit = metadataedit.New(m.styles, abs.LibraryItem{MediaType: "book"}) m.seriesList = serieslist.New(m.styles, m.client, "", "") m.series = series.New(m.styles, m.client, "", "", "") @@ -622,7 +660,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.handleCaptionLoaded(msg) case PlaySessionMsg: - logger.Info("play session started", "sessionID", msg.Session.SessionID, "itemID", msg.Session.ItemID, "episodeID", msg.Session.EpisodeID, "currentTime", msg.Session.CurrentTime, "duration", msg.Session.Duration) + logger.Info("play session started", "session", abs.SessionTag(msg.Session.SessionID), "itemID", msg.Session.ItemID, "episodeID", msg.Session.EpisodeID, "currentTime", msg.Session.CurrentTime, "duration", msg.Session.Duration) return m.handlePlaySessionMsg(msg) case RestoreSessionMsg: @@ -630,6 +668,10 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { logger.Debug("no session to restore") return m, nil } + if m.isPlaying() || m.playRequested { + logger.Info("skipping session restore: the user started a playback", "itemID", msg.Item.ID) + return m, nil + } logger.Info("restoring session", "itemID", msg.Item.ID, "savedEpisodeID", msg.SavedEpisodeID, "resolvedEpisodeID", func() string { if msg.Episode == nil { return "" @@ -640,6 +682,11 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, m.startRestorePlaybackCmd(msg) case RestorePlaySessionMsg: + if m.isPlaying() || m.playRequested { + session := msg.PlaySessionMsg.Session + logger.Info("closing restored session: the user started a playback", "session", abs.SessionTag(session.SessionID), "itemID", session.ItemID) + return m, closeRestoredSessionCmd(m.client, session.SessionID) + } m.restorePaused = true return m.handlePlaySessionMsg(msg.PlaySessionMsg) @@ -650,7 +697,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.handlePositionMsg(msg) case SyncTickMsg: - m, cmd := m.handleSyncTick() + m, cmd := m.handleSyncTick(msg) if m.cacheStore != nil && time.Since(m.lastEvict) > 5*time.Minute { _ = m.cacheStore.EvictExpired() m.lastEvict = time.Now() @@ -716,12 +763,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, m.mprisVolumeCmd() case mpris.SetRateMsg: - m.player.Speed = msg.Rate - m.syncMprisState() - if m.mpv != nil { - return m, tea.Batch(m.mprisPlaybackCmd(), player.SetSpeedCmd(m.mpv, msg.Rate)) - } - return m, m.mprisPlaybackCmd() + return m.setSpeed(msg.Rate) case PlaybackStoppedMsg: return m, nil @@ -732,6 +774,11 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, cmd case search.CacheReadyMsg: + // The palette shows the results of its query when the snapshot of its + // library is ready. + if libID, _ := m.currentLibraryForSearch(); msg.LibraryID == libID { + m.palette.Refresh() + } return m.updateScreen(msg) case SleepTimerExpiredMsg: @@ -767,6 +814,14 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m2, cmd, ok := m.checkUnauthorized(msg.Err); ok { return m2, cmd } + // A start that fails with no session, for example at the change + // of a track, ends the playback. Its sleep timer must not stop + // the next playback. + if !m.isPlaying() { + m.sleepDeadline = time.Time{} + m.sleepDuration = 0 + m.player.SleepRemaining = "" + } cmd := m.err.SetError(msg.Err) m.propagateSize() return m, cmd @@ -844,8 +899,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } if key.Matches(msg, m.keys.GlobalPalette) { - m.openGlobalPalette() - return m, nil + return m, m.openGlobalPalette() } if key.Matches(msg, m.keys.ChapterOverlay) { if m.canOpenChapterOverlay() { @@ -902,6 +956,16 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.updateScreen(msg) } +// setSpeed sets the speed of the player and tells MPRIS clients the rate. +func (m Model) setSpeed(speed float64) (Model, tea.Cmd) { + m.player.Speed = speed + m.syncMprisState() + if m.mpv != nil { + return m, tea.Batch(m.mprisPlaybackCmd(), player.SetSpeedCmd(m.mpv, speed)) + } + return m, m.mprisPlaybackCmd() +} + // --- Sleep timer --- var sleepDurations = []time.Duration{ @@ -1029,13 +1093,9 @@ func (m *Model) clearPlaybackSessionState() { m.playbackLibraryID = "" } -// isUnauthorized returns true if the error message indicates HTTP 401. +// isUnauthorized returns true if the server answered HTTP 401. func isUnauthorized(err error) bool { - if err == nil { - return false - } - msg := err.Error() - return strings.Contains(msg, "status 401") || strings.Contains(msg, "unauthorized") + return abs.IsHTTPStatus(err, http.StatusUnauthorized) } // checkUnauthorized checks if the error indicates a 401 response. @@ -1064,7 +1124,11 @@ func (m Model) checkUnauthorized(err error) (Model, tea.Cmd, bool) { return m, tea.Batch(stopCmd, initCmd), true } -func (m *Model) openGlobalPalette() { +// openGlobalPalette opens the palette. The search of the palette answers only +// from a snapshot that is ready, so if the snapshot of the library is not +// ready, it returns a command that builds it. CacheReadyMsg then shows the +// results of the query. +func (m *Model) openGlobalPalette() tea.Cmd { playerItems, navItems := m.buildStaticPaletteItems() contextItems := m.buildContextPaletteItems() @@ -1074,6 +1138,15 @@ func (m *Model) openGlobalPalette() { } items = append(items, navItems...) m.palette.Open(items, m.contentSearchFunc()) + + libID, libMediaType := m.currentLibraryForSearch() + if m.searchCache == nil || libID == "" { + return nil + } + if _, ok := m.searchCache.TryGetAll(libID, libMediaType); ok { + return nil + } + return m.searchCache.PrebuildCmd(libID, libMediaType) } func (m Model) contentSearchFunc() components.SearchFunc { @@ -1098,11 +1171,12 @@ func (m Model) contentSearchFunc() components.SearchFunc { } itemCopy := res items = append(items, components.PaletteItem{ - Label: label, - Action: components.ActionContentNavigate, - LibraryID: res.LibraryID, - ItemID: res.ID, - Data: itemCopy, + Label: label, + Action: components.ActionContentNavigate, + PlayAction: components.ActionPlayDirect, + LibraryID: res.LibraryID, + ItemID: res.ID, + Data: itemCopy, }) } return items @@ -1258,24 +1332,13 @@ func (m Model) handlePaletteAction(action components.PaletteAction, payload, lib return m.handleSeek(float64(m.config.Player.SeekSeconds)) case components.ActionSeekBackward: return m.handleSeek(-float64(m.config.Player.SeekSeconds)) + // The speed keys and MPRIS can set a speed out of the range of the + // palette, 0.25 to 3.0. Speed Up never lowers a speed, and Speed Down + // never raises one. case components.ActionSpeedUp: - m.player.Speed += 0.25 - if m.player.Speed > 3.0 { - m.player.Speed = 3.0 - } - if m.mpv != nil { - return m, player.SetSpeedCmd(m.mpv, m.player.Speed) - } - return m, nil + return m.setSpeed(max(m.player.Speed, min(m.player.Speed+0.25, 3.0))) case components.ActionSpeedDown: - m.player.Speed -= 0.25 - if m.player.Speed < 0.25 { - m.player.Speed = 0.25 - } - if m.mpv != nil { - return m, player.SetSpeedCmd(m.mpv, m.player.Speed) - } - return m, nil + return m.setSpeed(min(m.player.Speed, max(m.player.Speed-0.25, 0.25))) case components.ActionNextChapter: if len(m.chapters) > 0 { return m.seekToChapter(m.nextChapter()) @@ -1545,7 +1608,7 @@ func (m Model) handlePaletteAction(action components.PaletteAction, payload, lib } return m, nil case components.ActionBrowseSeries: - m.seriesList = serieslist.New(m.styles, m.client, m.home.SelectedLibraryID(), "") + m.seriesList = serieslist.New(m.styles, m.client, libraryID, payload) return m.navigate(ScreenSeriesList) case components.ActionSwitchLibrary: return m, nil @@ -1574,12 +1637,13 @@ func (m Model) prewarmCacheCmd() tea.Cmd { } } -func (m *Model) handleDeleteItem(cmd detail.DeleteItemCmd) (tea.Model, tea.Cmd) { +func (m Model) handleDeleteItem(cmd detail.DeleteItemCmd) (Model, tea.Cmd) { if m.client == nil { return m, nil } + client := m.client return m, func() tea.Msg { - err := m.client.DeleteItem(context.Background(), cmd.ItemID, false) + err := client.DeleteItem(context.Background(), cmd.ItemID, false) if err != nil { return components.ErrMsg{Err: fmt.Errorf("failed to delete item: %w", err)} } @@ -1587,12 +1651,13 @@ func (m *Model) handleDeleteItem(cmd detail.DeleteItemCmd) (tea.Model, tea.Cmd) } } -func (m *Model) handleDeleteEpisode(cmd detail.DeleteEpisodeCmd) (tea.Model, tea.Cmd) { +func (m Model) handleDeleteEpisode(cmd detail.DeleteEpisodeCmd) (Model, tea.Cmd) { if m.client == nil { return m, nil } + client := m.client return m, func() tea.Msg { - err := m.client.DeleteEpisode(context.Background(), cmd.ItemID, cmd.EpisodeID, false) + err := client.DeleteEpisode(context.Background(), cmd.ItemID, cmd.EpisodeID, false) if err != nil { return components.ErrMsg{Err: fmt.Errorf("failed to delete episode: %w", err)} } diff --git a/internal/app/model_test.go b/internal/app/model_test.go index 02a693e..99b754c 100644 --- a/internal/app/model_test.go +++ b/internal/app/model_test.go @@ -4,8 +4,10 @@ import ( "encoding/json" "errors" "fmt" + "io" "net/http" "net/http/httptest" + "path/filepath" "sync" "testing" "time" @@ -78,12 +80,6 @@ func (p *mockPlayer) Seek(seconds float64) error { p.position = seconds return nil } -func (p *mockPlayer) SeekRelative(seconds float64) error { - p.mu.Lock() - defer p.mu.Unlock() - p.position += seconds - return nil -} func (p *mockPlayer) SetSpeed(speed float64) error { p.mu.Lock() defer p.mu.Unlock() @@ -91,7 +87,6 @@ func (p *mockPlayer) SetSpeed(speed float64) error { return nil } func (p *mockPlayer) SetVolume(vol int) error { return nil } -func (p *mockPlayer) GetVolume() (int, error) { return 100, nil } func (p *mockPlayer) Quit() error { p.mu.Lock() defer p.mu.Unlock() @@ -223,8 +218,8 @@ func TestMetadataSavedUpdatesDetailQueueAndPlayer(t *testing.T) { result, cmd := m.Update(metadataedit.SavedMsg{ItemID: updated.ID, Item: &updated}) m = result.(Model) - if cmd != nil { - t.Fatalf("cmd = %v, want nil", cmd) + if cmd == nil || cmd() != (PrewarmDoneMsg{}) { + t.Fatalf("cmd = %v, want only the prewarm of the search cache", cmd) } if got := m.detail.Item().Media.Metadata.Title; got != "New Title" { t.Fatalf("detail title = %q, want New Title", got) @@ -267,8 +262,8 @@ func TestEpisodeMetadataSavedUpdatesDetailQueueAndPlayer(t *testing.T) { result, cmd := m.Update(metadataedit.SavedEpisodeMsg{ItemID: updated.ID, EpisodeID: "ep-1", Item: &updated}) m = result.(Model) - if cmd != nil { - t.Fatalf("cmd = %v, want nil", cmd) + if cmd == nil || cmd() != (PrewarmDoneMsg{}) { + t.Fatalf("cmd = %v, want only the prewarm of the search cache", cmd) } if got := m.detail.Episodes()[0].Title; got != "New Episode" { t.Fatalf("detail episode title = %q, want New Episode", got) @@ -313,8 +308,8 @@ func TestStaleMetadataSaveDoesNotCloseNewEditor(t *testing.T) { updatedA.Media.Metadata.Title = "Saved Book A" result, cmd = m.Update(metadataedit.SavedMsg{ItemID: itemA.ID, Generation: save.Generation, Item: &updatedA}) m = result.(Model) - if cmd != nil { - t.Fatalf("cmd = %v, want nil for stale save without MPRIS bridge", cmd) + if cmd == nil || cmd() != (PrewarmDoneMsg{}) { + t.Fatalf("cmd = %v, want only the prewarm of the search cache for stale save without MPRIS bridge", cmd) } if m.ActiveScreen() != ScreenMetadataEdit { t.Fatalf("ActiveScreen() = %v, want new editor to remain open", m.ActiveScreen()) @@ -512,7 +507,7 @@ func TestLoginCapturesGlobalKeys(t *testing.T) { func TestHelpKeyClosesHelpOnLoginScreen(t *testing.T) { m := newTestModelAuthenticated() result, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'?'}}) - result, _ = result.(Model).Update(components.ErrMsg{Err: errors.New("status 401")}) + result, _ = result.(Model).Update(components.ErrMsg{Err: &abs.HTTPStatusError{StatusCode: http.StatusUnauthorized}}) m = result.(Model) if m.ActiveScreen() != ScreenLogin || !m.help.Visible() { t.Fatalf("ActiveScreen() = %v, help open = %v, want ScreenLogin and true", m.ActiveScreen(), m.help.Visible()) @@ -1963,7 +1958,7 @@ func TestUnauthorizedPlaybackErrorRedirectsToLogin(t *testing.T) { m.screen = ScreenHome result, cmd := m.Update(PlaybackErrorMsg{ - Err: fmt.Errorf("unexpected status 401: unauthorized"), + Err: &abs.HTTPStatusError{StatusCode: http.StatusUnauthorized}, }) rm := result.(Model) if rm.screen != ScreenLogin { @@ -1983,7 +1978,7 @@ func TestUnauthorizedBookDetailErrorRedirectsToLogin(t *testing.T) { result, cmd := m.Update(BookDetailLoadedMsg{ ItemID: "item-1", - Err: fmt.Errorf("unauthorized status 401"), + Err: &abs.HTTPStatusError{StatusCode: http.StatusUnauthorized}, }) rm := result.(Model) if rm.screen != ScreenLogin { @@ -2071,14 +2066,22 @@ func TestErrorDismissOnKeypress(t *testing.T) { func TestErrorDismissMsg(t *testing.T) { m := newTestModelAuthenticated() - result, _ := m.Update(components.ErrMsg{Err: fmt.Errorf("test error")}) + result, _ := m.Update(components.ErrMsg{Err: fmt.Errorf("first error")}) m = result.(Model) - - result, _ = m.Update(components.ErrorDismissMsg{}) + result, _ = m.Update(components.ErrMsg{Err: fmt.Errorf("second error")}) m = result.(Model) + // The tick of the first error, generation 1, must not dismiss the second + // error. + result, _ = m.Update(components.ErrorDismissMsg{Generation: 1}) + m = result.(Model) + if !m.err.HasError() { + t.Fatal("the dismiss tick of the first error dismissed the second error") + } + result, _ = m.Update(components.ErrorDismissMsg{Generation: 2}) + m = result.(Model) if m.err.HasError() { - t.Error("error should be dismissed after ErrorDismissMsg") + t.Error("error should be dismissed after its ErrorDismissMsg") } } @@ -2088,7 +2091,7 @@ func TestHTTP401RedirectsToLogin(t *testing.T) { t.Fatal("should start at Home") } - result, _ := m.Update(components.ErrMsg{Err: fmt.Errorf("unexpected status 401: Unauthorized")}) + result, _ := m.Update(components.ErrMsg{Err: &abs.HTTPStatusError{StatusCode: http.StatusUnauthorized}}) rm := result.(Model) if rm.ActiveScreen() != ScreenLogin { @@ -2113,7 +2116,7 @@ func TestHTTP401ErrMsgHaltsPlayback(t *testing.T) { m.sleepDeadline = time.Now().Add(15 * time.Minute) m.sleepDuration = 15 * time.Minute - result, cmd := m.Update(components.ErrMsg{Err: fmt.Errorf("unexpected status 401: Unauthorized")}) + result, cmd := m.Update(components.ErrMsg{Err: &abs.HTTPStatusError{StatusCode: http.StatusUnauthorized}}) rm := result.(Model) if rm.screen != ScreenLogin { @@ -2151,7 +2154,7 @@ func TestHTTP401PlaybackErrorHaltsPlayback(t *testing.T) { m.queue = []QueueEntry{{Item: abs.LibraryItem{ID: "queued-1"}}} m.sleepDeadline = time.Now().Add(20 * time.Minute) - result, _ := m.Update(PlaybackErrorMsg{Err: fmt.Errorf("status 401: unauthorized")}) + result, _ := m.Update(PlaybackErrorMsg{Err: &abs.HTTPStatusError{StatusCode: http.StatusUnauthorized}}) rm := result.(Model) if rm.screen != ScreenLogin { @@ -2362,9 +2365,14 @@ func TestIsUnauthorized(t *testing.T) { want bool }{ {nil, false}, - {errors.New("unexpected status 401: Unauthorized"), true}, + {&abs.HTTPStatusError{StatusCode: http.StatusUnauthorized}, true}, + {fmt.Errorf("get item: %w", &abs.HTTPStatusError{StatusCode: http.StatusUnauthorized}), true}, {errors.New("something failed"), false}, - {errors.New("unauthorized access"), true}, + // Only the status of the response tells a 401: a body or a text can + // have the word. + {&abs.HTTPStatusError{StatusCode: http.StatusForbidden, Body: "unauthorized"}, false}, + {errors.New("unexpected status 401: Unauthorized"), false}, + {errors.New("unauthorized access"), false}, } for _, tt := range tests { if got := isUnauthorized(tt.err); got != tt.want { @@ -2376,3 +2384,192 @@ func TestIsUnauthorized(t *testing.T) { } } } + +// TestProgramModelHasMprisBridge verifies that the model that the program runs +// has the MPRIS bridge. main makes the program with the model and then calls +// SetProgram, as this test does. +func TestProgramModelHasMprisBridge(t *testing.T) { + // The bridge must not connect to the session bus of the desktop. + t.Setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path="+filepath.Join(t.TempDir(), "no-bus")) + m := NewWithPlayer(config.Default(), nil, nil, nil, &mockPlayer{}) + p := tea.NewProgram(m, tea.WithInput(nil), tea.WithOutput(io.Discard)) + m.SetProgram(p) + defer m.Cleanup() + + go p.Quit() + final, err := p.Run() + if err != nil { + t.Fatalf("Run() error: %v", err) + } + if final.(Model).mprisBridge() == nil { + t.Error("the model of the program has no MPRIS bridge") + } +} + +// TestSleepTimerStopsPlaybackAfterExpiryBetweenSessions verifies that the +// sleep timer stops the playback if it expires while pine has no session: a +// change of the track closes the session and opens a new one. +func TestSleepTimerStopsPlaybackAfterExpiryBetweenSessions(t *testing.T) { + m := newMprisPlaybackTestModel(true) + m.trackDuration = 1800 + m.sleepGeneration = 1 + m.sleepDuration = 15 * time.Minute + m.sleepDeadline = time.Now().Add(-time.Second) + + m, _ = m.restartPlaybackAt(1800) + result, _ := m.Update(SleepTimerExpiredMsg{Generation: 1}) + m = result.(Model) + result, _ = m.Update(PlaySessionMsg{Session: PlaySessionData{ + SessionID: "sess-next-track", + ItemID: "item-1", + Duration: 3600, + TrackStartOffset: 1800, + TrackDuration: 1800, + }}) + m = result.(Model) + result, _ = m.Update(player.PositionMsg{Position: 1, Duration: 1800, Generation: m.playGeneration}) + m = result.(Model) + + if m.isPlaying() { + t.Error("the playback continues after the sleep timer expired") + } + if !m.sleepDeadline.IsZero() { + t.Error("the sleep timer is still set after it stopped the playback") + } +} + +// TestSleepTimerOfFailedTrackChangeDoesNotStopNextPlayback verifies that the +// sleep timer stops only its own playback: a change of the track that fails +// ends the playback, and a playback that starts later continues. +func TestSleepTimerOfFailedTrackChangeDoesNotStopNextPlayback(t *testing.T) { + m := newMprisPlaybackTestModel(true) + m.trackDuration = 1800 + m.sleepGeneration = 1 + m.sleepDuration = 15 * time.Minute + m.sleepDeadline = time.Now().Add(-time.Second) + + m, _ = m.restartPlaybackAt(1800) + result, _ := m.Update(PlaybackErrorMsg{Err: errors.New("network down")}) + m = result.(Model) + result, _ = m.Update(SleepTimerExpiredMsg{Generation: 1}) + m = result.(Model) + result, _ = m.Update(PlaySessionMsg{Session: PlaySessionData{ + SessionID: "sess-other", + ItemID: "item-other", + Duration: 3600, + TrackDuration: 3600, + }}) + m = result.(Model) + result, _ = m.Update(player.PositionMsg{Position: 1, Duration: 3600, Generation: m.playGeneration}) + m = result.(Model) + + if !m.isPlaying() { + t.Error("the sleep timer of the failed playback stopped the next playback") + } +} + +// TestLibraryPaletteBrowseSeriesOpensLibraryOfScreen verifies that Browse +// Series of the palette on the library screen opens the series of the library +// that the screen shows, as the key s does. +func TestLibraryPaletteBrowseSeriesOpensLibraryOfScreen(t *testing.T) { + m := newTestModelAuthenticated() + libs := []abs.Library{{ID: "lib-a", Name: "A", MediaType: "book"}, {ID: "lib-b", Name: "B", MediaType: "book"}} + m.home, _ = m.home.Update(home.PersonalizedMsg{Libraries: libs, LibraryID: "lib-a"}) + m.library.Configure("lib-b", libs) + m.library.SetSize(80, 24) + m.library, _ = m.library.Update(library.LibraryItemsMsg{LibraryID: "lib-b", Total: 1, Items: []abs.LibraryItem{ + {ID: "b-1", LibraryID: "lib-b", MediaType: "book", Media: abs.Media{Metadata: abs.MediaMetadata{Title: "B one"}}}, + }}) + m.screen = ScreenLibrary + + var browse *components.PaletteItem + for _, item := range m.buildContextPaletteItems() { + if item.Action == components.ActionBrowseSeries { + browse = &item + } + } + if browse == nil { + t.Fatal("the palette of the library screen has no Browse Series") + } + m, _ = m.handlePaletteAction(browse.Action, browse.Payload, browse.LibraryID, browse.ItemID, browse.Data) + if got := m.seriesList.SelectedLibraryID(); got != "lib-b" { + t.Errorf("series list library = %q, want lib-b", got) + } +} + +// TestPaletteSpeedActions verifies that Speed Up of the palette does not lower +// a speed above the range of the palette, and Speed Down does not raise a speed +// below it: the speed keys and MPRIS can set such a speed. MPRIS gets the new +// speed. +func TestPaletteSpeedActions(t *testing.T) { + tests := []struct { + action components.PaletteAction + speed float64 + want float64 + }{ + {components.ActionSpeedUp, 1.0, 1.25}, + {components.ActionSpeedUp, 2.9, 3.0}, + {components.ActionSpeedUp, 3.5, 3.5}, + {components.ActionSpeedDown, 1.0, 0.75}, + {components.ActionSpeedDown, 0.3, 0.25}, + {components.ActionSpeedDown, 0.2, 0.2}, + } + for _, tt := range tests { + m := newMprisPlaybackTestModel(true) + m.player.Speed = tt.speed + m, _ = m.handlePaletteAction(tt.action, "", "", "", nil) + if m.player.Speed != tt.want { + t.Errorf("action %v at the speed %v: speed = %v, want %v", tt.action, tt.speed, m.player.Speed, tt.want) + } + if got := m.mprisState.PlayerSpeed(); got != tt.want { + t.Errorf("action %v at the speed %v: MPRIS speed = %v, want %v", tt.action, tt.speed, got, tt.want) + } + } +} + +// TestDeleteCmdsReturnModelValue verifies that Update returns a Model value +// for a delete request: main runs Cleanup only on a Model value. +func TestDeleteCmdsReturnModelValue(t *testing.T) { + m := newTestModelAuthenticated() + for _, msg := range []tea.Msg{ + detail.DeleteItemCmd{ItemID: "item-1"}, + detail.DeleteEpisodeCmd{ItemID: "pod-1", EpisodeID: "ep-1"}, + } { + result, cmd := m.Update(msg) + if _, ok := result.(Model); !ok { + t.Errorf("%T: Update returns %T, want Model", msg, result) + } + if cmd == nil { + t.Errorf("%T: Update returns no delete command", msg) + } + } +} + +// TestMetadataSavedKeepsDetailProgress verifies that a metadata save keeps the +// progress on the detail screen. The answer of the save has no progress of the +// user. +func TestMetadataSavedKeepsDetailProgress(t *testing.T) { + m := newTestModelAuthenticated() + item := abs.LibraryItem{ + ID: "item-1", + MediaType: "book", + Media: abs.Media{Metadata: abs.MediaMetadata{Title: "Old Title"}}, + UserMediaProgress: &abs.UserMediaProgress{Progress: 1, IsFinished: true}, + } + m.screen = ScreenDetail + m.detail = detail.New(m.styles, item) + updated := item + updated.Media.Metadata.Title = "New Title" + updated.UserMediaProgress = nil + + result, _ := m.Update(metadataedit.SavedMsg{ItemID: updated.ID, Item: &updated}) + m = result.(Model) + + got := m.detail.Item() + if got.Media.Metadata.Title != "New Title" { + t.Errorf("detail title = %q, want New Title", got.Media.Metadata.Title) + } + if got.UserMediaProgress == nil || !got.UserMediaProgress.IsFinished { + t.Errorf("detail progress = %+v, want the finished progress", got.UserMediaProgress) + } +} diff --git a/internal/app/mpris_linux_test.go b/internal/app/mpris_linux_test.go new file mode 100644 index 0000000..de2f899 --- /dev/null +++ b/internal/app/mpris_linux_test.go @@ -0,0 +1,180 @@ +//go:build linux + +package app + +import ( + "bufio" + "os" + "os/exec" + "strings" + "testing" + "time" + + "github.com/Thelost77/pine/internal/mpris" + "github.com/Thelost77/pine/internal/player" + "github.com/godbus/dbus/v5" +) + +// listenMpris starts the MPRIS server of m on a private D-Bus session bus. It +// returns the positions of the Seeked signals of the server, in microseconds. +// Without dbus-daemon the test skips. With PINE_REQUIRE_DBUS=1 it fails. +func listenMpris(t *testing.T, m *Model) <-chan int64 { + t.Helper() + path, err := exec.LookPath("dbus-daemon") + if err != nil { + if os.Getenv("PINE_REQUIRE_DBUS") == "1" { + t.Fatalf("dbus-daemon is required: %v", err) + } + t.Skipf("dbus-daemon is not available: %v", err) + } + daemon := exec.Command(path, "--session", "--nofork", "--print-address") + stdout, err := daemon.StdoutPipe() + if err != nil { + t.Fatalf("StdoutPipe() error: %v", err) + } + if err := daemon.Start(); err != nil { + t.Fatalf("start dbus-daemon: %v", err) + } + t.Cleanup(func() { + _ = daemon.Process.Kill() + _ = daemon.Wait() + }) + address, err := bufio.NewReader(stdout).ReadString('\n') + if err != nil { + t.Fatalf("read the address of dbus-daemon: %v", err) + } + address = strings.TrimSpace(address) + // The server must not connect to the session bus of the desktop. + t.Setenv("DBUS_SESSION_BUS_ADDRESS", address) + + bridge := mpris.NewBridge(nil, "pine") + state := m.mprisState + bridge.Bind(func() mpris.ModelAccessor { return state }, 0) + m.mprisLink.bridge = bridge + server := bridge.Server() + go func() { _ = server.Listen() }() + t.Cleanup(func() { _ = server.Stop() }) + + client, err := dbus.Connect(address) + if err != nil { + t.Fatalf("connect to the test bus: %v", err) + } + t.Cleanup(func() { _ = client.Close() }) + for _, member := range []string{"Seeked", "PropertiesChanged"} { + if err := client.AddMatchSignal(dbus.WithMatchMember(member)); err != nil { + t.Fatalf("AddMatchSignal(%s) error: %v", member, err) + } + } + signals := make(chan *dbus.Signal, 64) + client.Signal(signals) + + // The server sends a signal only after it has its connection. Send a + // change of the volume until a change arrives. + deadline := time.Now().Add(5 * time.Second) + for ready := false; !ready; { + if time.Now().After(deadline) { + t.Fatal("the MPRIS server sends no signal") + } + server.VolumeChanged() + select { + case sig := <-signals: + ready = sig.Name == "org.freedesktop.DBus.Properties.PropertiesChanged" + case <-time.After(50 * time.Millisecond): + } + } + + seeked := make(chan int64, 64) + go func() { + for sig := range signals { + if sig.Name == "org.mpris.MediaPlayer2.Player.Seeked" && len(sig.Body) == 1 { + if pos, ok := sig.Body[0].(int64); ok { + seeked <- pos + } + } + } + }() + return seeked +} + +// nextSeeked returns the position of the next Seeked signal, in microseconds. +func nextSeeked(t *testing.T, seeked <-chan int64) int64 { + t.Helper() + select { + case pos := <-seeked: + return pos + case <-time.After(5 * time.Second): + t.Fatal("no Seeked signal") + return 0 + } +} + +// TestMprisSeekedOnlyForSeek verifies that the position ticks of a playback +// send no Seeked signal, and that a seek sends Seeked with the new position. +// An MPRIS client computes the position of a playback from the rate. +func TestMprisSeekedOnlyForSeek(t *testing.T) { + m := newMprisPlaybackTestModel(true) + m.trackDuration = 3600 + seeked := listenMpris(t, &m) + + for pos := 101.0; pos <= 103; pos++ { + result, cmd := m.Update(player.PositionMsg{Position: pos, Duration: 3600, Generation: m.playGeneration}) + m = result.(Model) + executeBatchCmds(cmd) + } + result, cmd := m.Update(mpris.SeekRelativeMsg{OffsetSeconds: 30}) + m = result.(Model) + executeBatchCmds(cmd) + + if got := nextSeeked(t, seeked); got != 133_000_000 { + t.Errorf("first Seeked position = %d µs, want 133000000 µs (the seek)", got) + } +} + +// TestMprisSeekedForStartAtPosition verifies that a playback that starts at a +// position after the start of the book sends Seeked with that position. +func TestMprisSeekedForStartAtPosition(t *testing.T) { + m := newPlaybackTestModel() + seeked := listenMpris(t, &m) + + result, cmd := m.Update(PlaySessionMsg{Session: PlaySessionData{ + SessionID: "sess-123", + ItemID: "item-1", + CurrentTime: 300, + Duration: 3600, + Title: "A Book", + TrackDuration: 3600, + }}) + m = result.(Model) + executeBatchCmds(cmd) + + if got := nextSeeked(t, seeked); got != 300_000_000 { + t.Errorf("Seeked position = %d µs, want 300000000 µs", got) + } +} + +// TestMprisSeekedForRestartAtStart verifies that a restart of the item at the +// start of the book sends Seeked, for example a seek from a later file of the +// book to the first chapter. The track ID does not change. +func TestMprisSeekedForRestartAtStart(t *testing.T) { + m := newMprisPlaybackTestModel(true) + seeked := listenMpris(t, &m) + // The item plays the second file, at the book position 2000. + m.trackStartOffset = 1800 + m.trackDuration = 1800 + m.player.Position = 2000 + m.syncMprisState() + + m, _ = m.restartPlaybackAt(0) + result, cmd := m.Update(PlaySessionMsg{Session: PlaySessionData{ + SessionID: "sess-restart", + ItemID: "item-1", + Duration: 3600, + TrackDuration: 1800, + }}) + m = result.(Model) + executeBatchCmds(cmd) + + if got := nextSeeked(t, seeked); got != 0 { + t.Errorf("Seeked position = %d µs, want 0 µs", got) + } +} diff --git a/internal/app/mpris_messages_test.go b/internal/app/mpris_messages_test.go index 20536cc..738399b 100644 --- a/internal/app/mpris_messages_test.go +++ b/internal/app/mpris_messages_test.go @@ -124,3 +124,46 @@ func TestMprisPauseAndPlayMsgSendTheStateToThePlayer(t *testing.T) { t.Error("PlayMsg should resume the player") } } + +// TestPositionTickUpdatesMprisPosition verifies that the MPRIS property +// Position follows the position ticks of a playback. +func TestPositionTickUpdatesMprisPosition(t *testing.T) { + m := newMprisPlaybackTestModel(true) + m.syncMprisState() + + m = listen(playingNow(m), 130) + + if got := m.mprisState.PlayerPosition(); got != 130 { + t.Errorf("MPRIS position = %v; want 130", got) + } +} + +// TestMprisTrackIDOfEpisode verifies that each episode of a podcast is a track +// of its own for MPRIS, also after the playback stops. +func TestMprisTrackIDOfEpisode(t *testing.T) { + m := newPlaybackTestModel() + play := func(m Model, episodeID string) Model { + result, _ := m.Update(PlaySessionMsg{Session: PlaySessionData{ + SessionID: "sess-" + episodeID, + ItemID: "pod-1", + EpisodeID: episodeID, + Duration: 1800, + TrackDuration: 1800, + }}) + return result.(Model) + } + + m = play(m, "ep-1") + first := m.mprisState.CurrentItemID() + m, _ = m.stopPlayback() + m = play(m, "ep-2") + second := m.mprisState.CurrentItemID() + if first == second { + t.Errorf("the episodes ep-1 and ep-2 have the same MPRIS track %q", first) + } + + m, _ = m.stopPlayback() + if got := m.mprisState.CurrentItemID(); got != second { + t.Errorf("MPRIS track after the stop = %q, want %q", got, second) + } +} diff --git a/internal/app/playback.go b/internal/app/playback.go index 2b82d85..124de30 100644 --- a/internal/app/playback.go +++ b/internal/app/playback.go @@ -3,7 +3,6 @@ package app import ( "context" "errors" - "fmt" "math" "net/http" "runtime/debug" @@ -37,6 +36,9 @@ const ( syncMinChange = 1.0 ) +// errNoAudioTracks is the error of a play session that has no audio track. +var errNoAudioTracks = errors.New("no audio tracks") + func pineVersion() string { if info, ok := debug.ReadBuildInfo(); ok { return buildVersion(info.Main.Version) @@ -152,11 +154,10 @@ func (m Model) handlePlayCmd(msg detail.PlayCmd) (Model, tea.Cmd) { return m, nil } - m.setSeriesContext(msg.Item) - if m.client == nil { return m, nil } + m.playRequested = true // Different item playing → stop it first var closeCmd, stopCmd tea.Cmd @@ -209,12 +210,10 @@ func (m Model) handlePlayEpisodeCmd(msg detail.PlayEpisodeCmd) (Model, tea.Cmd) return m, nil } - m.playbackSeriesID = "" - m.playbackLibraryID = "" - if m.client == nil { return m, nil } + m.playRequested = true // Different item/episode playing → stop it first var closeCmd, stopCmd tea.Cmd @@ -223,6 +222,10 @@ func (m Model) handlePlayEpisodeCmd(msg detail.PlayEpisodeCmd) (Model, tea.Cmd) m, closeCmd, stopCmd = m.stopPlaybackCmds() } + // An episode has no series to continue. + m.playbackSeriesID = "" + m.playbackLibraryID = msg.Item.LibraryID + item := msg.Item episode := msg.Episode client := m.client @@ -247,6 +250,9 @@ func (m Model) handlePlayEpisodeCmd(msg detail.PlayEpisodeCmd) (Model, tea.Cmd) // handlePlaySessionMsg launches mpv with the stream URL. func (m Model) handlePlaySessionMsg(msg PlaySessionMsg) (Model, tea.Cmd) { + // restartPlaybackAt keeps the item, so a session of the same item is a + // restart, for example at a seek to another file of the book. + restart := m.itemID == msg.Session.ItemID && m.episodeID == msg.Session.EpisodeID m.playGeneration++ m.sessionID = msg.Session.SessionID m.itemID = msg.Session.ItemID @@ -269,7 +275,7 @@ func (m Model) handlePlaySessionMsg(msg PlaySessionMsg) (Model, tea.Cmd) { m.player.Duration = msg.Session.Duration m.propagateSize() m.syncMprisState() - logger.Info("playback session loaded", "sessionID", msg.Session.SessionID, "itemID", msg.Session.ItemID, "episodeID", msg.Session.EpisodeID, "bookPosition", bookPos, "trackStart", msg.Session.TrackStartOffset, "trackDuration", msg.Session.TrackDuration, "chapters", len(msg.Session.Chapters), "pausedRestore", m.restorePaused) + logger.Info("playback session loaded", "session", abs.SessionTag(msg.Session.SessionID), "itemID", msg.Session.ItemID, "episodeID", msg.Session.EpisodeID, "bookPosition", bookPos, "trackStart", msg.Session.TrackStartOffset, "trackDuration", msg.Session.TrackDuration, "chapters", len(msg.Session.Chapters), "pausedRestore", m.restorePaused) paused := m.restorePaused m.restorePaused = false @@ -279,9 +285,14 @@ func (m Model) handlePlaySessionMsg(msg PlaySessionMsg) (Model, tea.Cmd) { } cmds := []tea.Cmd{ m.mprisPlaybackCmd(), - player.LaunchCmd(m.mpv, msg.StreamURL, msg.Session.CurrentTime, msg.Session.TrackDuration, paused, headers, m.player.Volume, m.playGeneration), + player.LaunchCmd(m.mpv, msg.StreamURL, msg.Session.CurrentTime, paused, headers, m.player.Volume, m.playGeneration), + } + // An MPRIS client expects a new track at the position 0. A restart keeps + // the track ID, so it sends Seeked also at the position 0. + if bookPos > 0 || restart { + cmds = append(cmds, m.mprisSeekedCmd()) } - if capCmd := loadCaptionsCmd(m.client, msg.Session.ItemID, msg.Session.TrackFilename, msg.Session.TranscriptIno, m.playGeneration); capCmd != nil { + if capCmd := loadCaptionsCmd(m.client, msg.Session.ItemID, msg.Session.TrackFilename, msg.Session.TranscriptIno, msg.Session.HasLibraryFiles, m.playGeneration); capCmd != nil { cmds = append(cmds, capCmd) } return m, tea.Batch(cmds...) @@ -308,8 +319,12 @@ func (m *Model) toggleCaptions() { m.propagateSize() } -func loadCaptionsCmd(client *cache.Client, itemID, audioFilename, ino string, generation uint64) tea.Cmd { - if client == nil || itemID == "" { +// loadCaptionsCmd loads the VTT file ino. If ino is empty, it finds the VTT +// file of audioFilename in the files of the item. hasFiles is true if the play +// session gave the files of the item: ino is then complete, and an empty ino +// means that the item has no VTT file. +func loadCaptionsCmd(client *cache.Client, itemID, audioFilename, ino string, hasFiles bool, generation uint64) tea.Cmd { + if client == nil || itemID == "" || (ino == "" && hasFiles) { return nil } inner := client.Client @@ -349,7 +364,7 @@ func (m Model) handlePlayerReady(msg player.PlayerReadyMsg) (Model, tea.Cmd) { return m, tea.Batch( player.SetSpeedCmd(m.mpv, m.player.Speed), player.TickCmd(m.mpv, m.playGeneration), - syncTickCmd(), + syncTickCmd(m.playGeneration), ) } @@ -421,7 +436,6 @@ func (m Model) handlePositionMsg(msg player.PositionMsg) (Model, tea.Cmd) { m.syncMprisState() mprisCmds = append(mprisCmds, m.mprisPlaybackCmd()) } - mprisCmds = append(mprisCmds, m.mprisPositionCmd()) if m.mpv != nil { return m, tea.Batch(append(mprisCmds, player.TickCmd(m.mpv, m.playGeneration))...) } @@ -431,21 +445,23 @@ func (m Model) handlePositionMsg(msg player.PositionMsg) (Model, tea.Cmd) { m.player.Position = bookPos wasPlaying := m.player.Playing m.player.Playing = !msg.Paused + // MPRIS clients read the position from the state. + m.syncMprisState() var mprisCmds []tea.Cmd if wasPlaying != m.player.Playing { - m.syncMprisState() mprisCmds = append(mprisCmds, m.mprisPlaybackCmd()) } - mprisCmds = append(mprisCmds, m.mprisPositionCmd()) - // Update sleep timer display + // Update sleep timer display. Update drops SleepTimerExpiredMsg while pine + // has no session, for example at the change of a track, so a tick after + // the deadline stops the playback. if !m.sleepDeadline.IsZero() { remaining := time.Until(m.sleepDeadline) if remaining <= 0 { - m.player.SleepRemaining = "" - } else { - m.player.SleepRemaining = formatSleepRemaining(remaining) + logger.Info("sleep timer expired, stopping playback") + return m.stopPlayback() } + m.player.SleepRemaining = formatSleepRemaining(remaining) } if m.mpv != nil { @@ -551,6 +567,7 @@ func (m Model) startPlaybackAtBookPositionCmd(item abs.LibraryItem, bookPos floa // playItemAt plays a book, or an episode of a podcast, from a position in the // book or the episode. A different item or episode that plays stops first. func (m Model) playItemAt(item abs.LibraryItem, episode *abs.PodcastEpisode, pos float64) (Model, tea.Cmd) { + m.playRequested = true var closeCmd, stopCmd tea.Cmd if m.isPlaying() { episodeID := "" @@ -608,6 +625,20 @@ func (m Model) startRestorePlaybackCmd(msg RestoreSessionMsg) tea.Cmd { return m.startRestoredBookPlaybackCmd(*msg.Item) } +// closeRestoredSessionCmd closes a session that the restore opened and that +// pine does not play. The session has no position to send. +func closeRestoredSessionCmd(client *cache.Client, sessionID string) tea.Cmd { + if client == nil || sessionID == "" { + return nil + } + return func() tea.Msg { + if err := client.CloseSessionNoSync(context.Background(), sessionID); err != nil { + logger.Warn("failed to close restored session", "session", abs.SessionTag(sessionID), "err", err) + } + return nil + } +} + func (m Model) startRestoredBookPlaybackCmd(item abs.LibraryItem) tea.Cmd { client := m.client store := m.db @@ -637,16 +668,16 @@ func (m Model) startRestoredBookPlaybackCmd(item abs.LibraryItem) tea.Cmd { session.CurrentTime, ) if err != nil { - if err.Error() == "no audio tracks" { + if errors.Is(err, errNoAudioTracks) { clearSavedRestoreSession( store, "book playback returned no audio tracks", "itemID", item.ID, - "sessionID", session.ID, + "session", abs.SessionTag(session.ID), ) return nil } - logSkippedRestore("book playback session invalid", "itemID", item.ID, "sessionID", session.ID, "err", err) + logSkippedRestore("book playback session invalid", "itemID", item.ID, "session", abs.SessionTag(session.ID), "err", err) return nil } return RestorePlaySessionMsg{PlaySessionMsg: playMsg} @@ -673,41 +704,22 @@ func (m Model) startRestoredEpisodePlaybackCmd(item abs.LibraryItem, episode abs logSkippedRestore("podcast episode playback start failed", "itemID", item.ID, "episodeID", episode.ID, "err", err) return nil } - if len(session.AudioTracks) == 0 { - clearSavedRestoreSession( - store, - "podcast episode playback returned no audio tracks", - "itemID", item.ID, - "episodeID", episode.ID, - "sessionID", session.ID, - ) + playMsg, err := buildEpisodePlaySessionMsg(client, session, item, episode, session.CurrentTime) + if err != nil { + if errors.Is(err, errNoAudioTracks) { + clearSavedRestoreSession( + store, + "podcast episode playback returned no audio tracks", + "itemID", item.ID, + "episodeID", episode.ID, + "session", abs.SessionTag(session.ID), + ) + return nil + } + logSkippedRestore("podcast episode playback session invalid", "itemID", item.ID, "episodeID", episode.ID, "session", abs.SessionTag(session.ID), "err", err) return nil } - - streamURL := client.BaseURL() + session.AudioTracks[0].ContentURL - logger.Info("track selected for episode playback", "itemID", item.ID, "episodeID", episode.ID, "sessionID", session.ID, "trackIndex", session.AudioTracks[0].Index, "trackStart", session.AudioTracks[0].StartOffset, "trackDuration", session.AudioTracks[0].Duration, "bookPosition", session.CurrentTime) - - return RestorePlaySessionMsg{ - PlaySessionMsg: PlaySessionMsg{ - Session: PlaySessionData{ - SessionID: session.ID, - ItemID: item.ID, - EpisodeID: episode.ID, - CurrentTime: session.CurrentTime, - SyncedTime: session.CurrentTime, - Duration: resolveEpisodeDuration(episode, session), - Title: episode.Title, - Authors: mprisAuthors(item), - Chapters: playSessionChapters(session), - TrackStartOffset: session.AudioTracks[0].StartOffset, - TrackDuration: session.AudioTracks[0].Duration, - TrackFilename: session.AudioTracks[0].Metadata.Filename, - TranscriptIno: session.TranscriptIno(session.AudioTracks[0].Metadata.Filename), - }, - StreamURL: streamURL, - AuthToken: client.Token(), - }, - } + return RestorePlaySessionMsg{PlaySessionMsg: playMsg} } } @@ -759,11 +771,16 @@ func (m Model) startQueuedEntry(next QueueEntry, closeCmd, stopCmd tea.Cmd) (Mod func buildBookPlaySessionMsg(client *cache.Client, session *abs.PlaySession, itemID, title string, authors []string, duration, bookPos float64) (PlaySessionMsg, error) { if len(session.AudioTracks) == 0 { - return PlaySessionMsg{}, fmt.Errorf("no audio tracks") + return PlaySessionMsg{}, errNoAudioTracks } track := session.AudioTracks[0] seekTime := bookPos + // A position at the end of the book is the end of the last track. + if last := session.AudioTracks[len(session.AudioTracks)-1]; bookPos >= last.StartOffset+last.Duration { + track = last + seekTime = last.Duration + } for _, t := range session.AudioTracks { if bookPos >= t.StartOffset && bookPos < t.StartOffset+t.Duration { track = t @@ -771,7 +788,7 @@ func buildBookPlaySessionMsg(client *cache.Client, session *abs.PlaySession, ite break } } - logger.Info("track selected for playback", "itemID", itemID, "sessionID", session.ID, "trackIndex", track.Index, "trackStart", track.StartOffset, "trackDuration", track.Duration, "bookPosition", bookPos, "seekTime", seekTime) + logger.Info("track selected for playback", "itemID", itemID, "session", abs.SessionTag(session.ID), "trackIndex", track.Index, "trackStart", track.StartOffset, "trackDuration", track.Duration, "bookPosition", bookPos, "seekTime", seekTime) streamURL := client.BaseURL() + track.ContentURL @@ -789,6 +806,7 @@ func buildBookPlaySessionMsg(client *cache.Client, session *abs.PlaySession, ite TrackDuration: track.Duration, TrackFilename: track.Metadata.Filename, TranscriptIno: session.TranscriptIno(track.Metadata.Filename), + HasLibraryFiles: len(session.LibraryItem.LibraryFiles) > 0, }, StreamURL: streamURL, AuthToken: client.Token(), @@ -799,12 +817,12 @@ func buildBookPlaySessionMsg(client *cache.Client, session *abs.PlaySession, ite // episode at the position pos. func buildEpisodePlaySessionMsg(client *cache.Client, session *abs.PlaySession, item abs.LibraryItem, episode abs.PodcastEpisode, pos float64) (PlaySessionMsg, error) { if len(session.AudioTracks) == 0 { - return PlaySessionMsg{}, fmt.Errorf("no audio tracks") + return PlaySessionMsg{}, errNoAudioTracks } track := session.AudioTracks[0] streamURL := client.BaseURL() + track.ContentURL - logger.Info("track selected for episode playback", "itemID", item.ID, "episodeID", episode.ID, "sessionID", session.ID, "trackIndex", track.Index, "trackStart", track.StartOffset, "trackDuration", track.Duration, "bookPosition", pos) + logger.Info("track selected for episode playback", "itemID", item.ID, "episodeID", episode.ID, "session", abs.SessionTag(session.ID), "trackIndex", track.Index, "trackStart", track.StartOffset, "trackDuration", track.Duration, "bookPosition", pos) return PlaySessionMsg{ Session: PlaySessionData{ @@ -821,6 +839,7 @@ func buildEpisodePlaySessionMsg(client *cache.Client, session *abs.PlaySession, TrackDuration: track.Duration, TrackFilename: track.Metadata.Filename, TranscriptIno: session.TranscriptIno(track.Metadata.Filename), + HasLibraryFiles: len(session.LibraryItem.LibraryFiles) > 0, }, StreamURL: streamURL, AuthToken: client.Token(), @@ -848,9 +867,11 @@ func resolveEpisodeDuration(episode abs.PodcastEpisode, session *abs.PlaySession return duration } -// handleSyncTick syncs progress with ABS and persists to DB. -func (m Model) handleSyncTick() (Model, tea.Cmd) { - if !m.isPlaying() { +// handleSyncTick syncs progress with ABS and persists to DB. A tick of an +// earlier playback ends its chain of ticks: each playback starts its own chain +// in handlePlayerReady. +func (m Model) handleSyncTick(msg SyncTickMsg) (Model, tea.Cmd) { + if msg.Generation != m.playGeneration || !m.isPlaying() { return m, nil } @@ -860,23 +881,19 @@ func (m Model) handleSyncTick() (Model, tea.Cmd) { episodeID := m.episodeID currentTime := m.player.Position timeListened := m.timeListened - duration := m.player.Duration store := m.db cmds := []tea.Cmd{ - syncTickCmd(), + syncTickCmd(m.playGeneration), func() tea.Msg { if store != nil { if err := store.SaveListeningSession(db.ListeningSession{ - ItemID: itemID, - EpisodeID: episodeID, - SessionID: sessionID, - CurrentTime: currentTime, - Duration: duration, + ItemID: itemID, + EpisodeID: episodeID, }); err != nil { - logger.Warn("failed to save listening session", "itemID", itemID, "sessionID", sessionID, "currentTime", currentTime, "duration", duration, "err", err) + logger.Warn("failed to save listening session", "itemID", itemID, "err", err) } else { - logger.Debug("listening session saved", "itemID", itemID, "sessionID", sessionID, "currentTime", currentTime, "duration", duration) + logger.Debug("listening session saved", "itemID", itemID) } } return nil @@ -907,7 +924,7 @@ func syncSessionCmd(client *cache.Client, device abs.DeviceInfo, sessionID, item msg := SessionSyncedMsg{SessionID: sessionID, CurrentTime: currentTime, TimeListened: timeListened} msg.Err = client.SyncSession(ctx, sessionID, currentTime, timeListened) if abs.IsHTTPStatus(msg.Err, http.StatusNotFound) { - logger.Info("session is gone on the server, opening a new session", "sessionID", sessionID, "itemID", itemID, "episodeID", episodeID) + logger.Info("session is gone on the server, opening a new session", "session", abs.SessionTag(sessionID), "itemID", itemID, "episodeID", episodeID) var session *abs.PlaySession if episodeID != "" { session, msg.Err = client.StartEpisodePlaySession(ctx, itemID, episodeID, device) @@ -919,10 +936,14 @@ func syncSessionCmd(client *cache.Client, device abs.DeviceInfo, sessionID, item msg.Err = client.SyncSession(ctx, session.ID, currentTime, timeListened) } } + fields := []any{"session", abs.SessionTag(sessionID), "currentTime", currentTime, "timeListened", timeListened} + if msg.NewSessionID != "" { + fields = append(fields, "newSession", abs.SessionTag(msg.NewSessionID)) + } if msg.Err != nil { - logger.Warn("failed to sync session", "sessionID", sessionID, "newSessionID", msg.NewSessionID, "currentTime", currentTime, "timeListened", timeListened, "err", msg.Err) + logger.Warn("failed to sync session", append(fields, "err", msg.Err)...) } else { - logger.Debug("session synced", "sessionID", sessionID, "newSessionID", msg.NewSessionID, "currentTime", currentTime, "timeListened", timeListened) + logger.Debug("session synced", fields...) } return msg } @@ -968,6 +989,10 @@ func (m Model) handleMarkFinished(msg detail.MarkFinishedCmd) (Model, tea.Cmd) { client := m.client item := msg.Item episode := msg.Episode + episodeID := "" + if episode != nil { + episodeID = episode.ID + } cacheStore := m.cacheStore itemID := item.ID libraryID := item.LibraryID @@ -978,17 +1003,13 @@ func (m Model) handleMarkFinished(msg detail.MarkFinishedCmd) (Model, tea.Cmd) { return m, func() tea.Msg { var err error if msg.Undo { - if episode != nil { - err = client.UpdateEpisodeProgress(context.Background(), item.ID, episode.ID, 0, 0, false) - } else { - err = client.UpdateProgress(context.Background(), item.ID, 0, 0, false) - } + err = client.UpdateProgress(context.Background(), item.ID, episodeID, 0, 0, false) if err != nil { logger.Warn("failed to unmark finished", "err", err) return PlaybackErrorMsg{Err: err} } evictProgressCaches(cacheStore, itemID, libraryID, seriesID) - return detail.MarkFinishedMsg{Progress: &abs.UserMediaProgress{ + return detail.MarkFinishedMsg{EpisodeID: episodeID, Progress: &abs.UserMediaProgress{ IsFinished: false, }} } @@ -996,11 +1017,7 @@ func (m Model) handleMarkFinished(msg detail.MarkFinishedCmd) (Model, tea.Cmd) { if episode != nil && episode.Duration > 0 { duration = episode.Duration } - if episode != nil { - err = client.UpdateEpisodeProgress(context.Background(), item.ID, episode.ID, duration, 1.0, true) - } else { - err = client.UpdateProgress(context.Background(), item.ID, duration, 1.0, true) - } + err = client.UpdateProgress(context.Background(), item.ID, episodeID, duration, 1.0, true) if err != nil { logger.Warn("failed to mark as finished", "err", err) return PlaybackErrorMsg{Err: err} @@ -1011,7 +1028,7 @@ func (m Model) handleMarkFinished(msg detail.MarkFinishedCmd) (Model, tea.Cmd) { Progress: 1.0, IsFinished: true, } - return detail.MarkFinishedMsg{Progress: progress} + return detail.MarkFinishedMsg{EpisodeID: episodeID, Progress: progress} } } @@ -1053,7 +1070,7 @@ func (m Model) stopPlayback() (Model, tea.Cmd) { // close of the session apart from the other cleanup commands, so that a // caller can run a play request after the close with closeThen. func (m Model) stopPlaybackCmds() (Model, tea.Cmd, tea.Cmd) { - logger.Info("stopping playback", "sessionID", m.sessionID, "itemID", m.itemID, "episodeID", m.episodeID, "position", m.player.Position, "duration", m.player.Duration, "timeListened", m.timeListened) + logger.Info("stopping playback", "session", abs.SessionTag(m.sessionID), "itemID", m.itemID, "episodeID", m.episodeID, "position", m.player.Position, "duration", m.player.Duration, "timeListened", m.timeListened) client := m.client sessionID := m.sessionID itemID := m.itemID @@ -1070,7 +1087,7 @@ func (m Model) stopPlaybackCmds() (Model, tea.Cmd, tea.Cmd) { // Cache last played item for MPRIS metadata after stop m.lastPlayedTitle = m.player.Title - m.lastPlayedItemID = m.itemID + m.lastPlayedTrackID = mprisTrackID(m.itemID, m.episodeID) m.lastPlayedAuthors = m.currentAuthors // Clear session state @@ -1090,9 +1107,9 @@ func (m Model) stopPlaybackCmds() (Model, tea.Cmd, tea.Cmd) { closeCmd := func() tea.Msg { if client != nil && sessionID != "" { if err := closeSession(context.Background(), client, sessionID, currentTime, timeListened, changed); err != nil { - logger.Warn("failed to close session", "sessionID", sessionID, "currentTime", currentTime, "timeListened", timeListened, "changed", changed, "err", err) + logger.Warn("failed to close session", "session", abs.SessionTag(sessionID), "currentTime", currentTime, "timeListened", timeListened, "changed", changed, "err", err) } else { - logger.Debug("session closed", "sessionID", sessionID, "currentTime", currentTime, "timeListened", timeListened, "changed", changed) + logger.Debug("session closed", "session", abs.SessionTag(sessionID), "currentTime", currentTime, "timeListened", timeListened, "changed", changed) } } invalidateCache() @@ -1115,15 +1132,12 @@ func (m Model) stopPlaybackCmds() (Model, tea.Cmd, tea.Cmd) { func() tea.Msg { if store != nil && itemID != "" { if err := store.SaveListeningSession(db.ListeningSession{ - ItemID: itemID, - EpisodeID: episodeID, - SessionID: sessionID, - CurrentTime: currentTime, - Duration: duration, + ItemID: itemID, + EpisodeID: episodeID, }); err != nil { - logger.Warn("failed to save listening session on stop", "itemID", itemID, "sessionID", sessionID, "currentTime", currentTime, "duration", duration, "err", err) + logger.Warn("failed to save listening session on stop", "itemID", itemID, "err", err) } else { - logger.Debug("listening session saved on stop", "itemID", itemID, "sessionID", sessionID, "currentTime", currentTime, "duration", duration) + logger.Debug("listening session saved on stop", "itemID", itemID) } } return nil @@ -1148,8 +1162,8 @@ func playSessionChapters(session *abs.PlaySession) []abs.Chapter { // Cleanup performs synchronous cleanup of playback resources. func (m Model) Cleanup() { - if m.mprisBridge != nil { - _ = m.mprisBridge.Stop() + if bridge := m.mprisBridge(); bridge != nil { + _ = bridge.Stop() } if m.mpv != nil { _ = m.mpv.Quit() @@ -1178,9 +1192,9 @@ func (m Model) Cleanup() { if m.client != nil && m.sessionID != "" { if err := closeSession(ctx, m.client, m.sessionID, currentTime, timeListened, changed); err != nil { - logger.Warn("cleanup: failed to close session", "sessionID", m.sessionID, "currentTime", currentTime, "timeListened", timeListened, "changed", changed, "err", err) + logger.Warn("cleanup: failed to close session", "session", abs.SessionTag(m.sessionID), "currentTime", currentTime, "timeListened", timeListened, "changed", changed, "err", err) } else { - logger.Debug("cleanup: session closed", "sessionID", m.sessionID, "currentTime", currentTime, "timeListened", timeListened, "changed", changed) + logger.Debug("cleanup: session closed", "session", abs.SessionTag(m.sessionID), "currentTime", currentTime, "timeListened", timeListened, "changed", changed) } evictProgressCaches(m.cacheStore, itemID, libraryID, seriesID) } @@ -1197,23 +1211,21 @@ func (m Model) Cleanup() { if m.db != nil && m.itemID != "" { if err := m.db.SaveListeningSession(db.ListeningSession{ - ItemID: m.itemID, - EpisodeID: m.episodeID, - SessionID: m.sessionID, - CurrentTime: currentTime, - Duration: duration, + ItemID: m.itemID, + EpisodeID: m.episodeID, }); err != nil { - logger.Warn("cleanup: failed to save listening session", "itemID", m.itemID, "episodeID", m.episodeID, "sessionID", m.sessionID, "currentTime", currentTime, "duration", duration, "err", err) + logger.Warn("cleanup: failed to save listening session", "itemID", m.itemID, "episodeID", m.episodeID, "err", err) } else { - logger.Debug("cleanup: listening session saved", "itemID", m.itemID, "episodeID", m.episodeID, "sessionID", m.sessionID, "currentTime", currentTime, "duration", duration) + logger.Debug("cleanup: listening session saved", "itemID", m.itemID, "episodeID", m.episodeID) } } } // syncTickCmd returns a command that fires SyncTickMsg after the sync interval. -func syncTickCmd() tea.Cmd { +// generation is the playGeneration of the playback. +func syncTickCmd(generation uint64) tea.Cmd { return tea.Tick(syncInterval, func(_ time.Time) tea.Msg { - return SyncTickMsg{} + return SyncTickMsg{Generation: generation} }) } @@ -1280,13 +1292,14 @@ func logSkippedRestore(reason string, keyvals ...any) { logger.Info("skipping session restore", fields...) } +// setSeriesContext records the library and the series of the item that +// starts. The library is also the library of an item with no series: the +// home shelves of the library show the progress of the item. func (m *Model) setSeriesContext(item abs.LibraryItem) { + m.playbackLibraryID = item.LibraryID + m.playbackSeriesID = "" if item.Media.Metadata.Series != nil { m.playbackSeriesID = item.Media.Metadata.Series.ID - m.playbackLibraryID = item.LibraryID - } else { - m.playbackSeriesID = "" - m.playbackLibraryID = "" } } diff --git a/internal/app/playback_test.go b/internal/app/playback_test.go index e0950a8..bce697d 100644 --- a/internal/app/playback_test.go +++ b/internal/app/playback_test.go @@ -248,7 +248,7 @@ func TestPlaybackLifecycleIntegration(t *testing.T) { } // --- Step 6: Inject SyncTickMsg → verify sync fires --- - result, cmd = m.Update(SyncTickMsg{}) + result, cmd = m.Update(SyncTickMsg{Generation: m.playGeneration}) m = result.(Model) if cmd == nil { @@ -1662,14 +1662,14 @@ func TestSeriesContinueAPIErrorShowsBanner(t *testing.T) { } func TestEpisodePlaybackClearsSeriesContext(t *testing.T) { - mp := &mockPlayer{} - m := NewWithPlayer(config.Default(), nil, nil, nil, mp) + m := newPlaybackTestModel() m.playbackSeriesID = "series-prev" m.playbackLibraryID = "lib-prev" m, _ = m.handlePlayEpisodeCmd(detail.PlayEpisodeCmd{ Item: abs.LibraryItem{ ID: "pod-001", + LibraryID: "lib-pod", MediaType: "podcast", Media: abs.Media{ Metadata: abs.MediaMetadata{Title: "Podcast Show"}, @@ -1684,8 +1684,8 @@ func TestEpisodePlaybackClearsSeriesContext(t *testing.T) { if m.playbackSeriesID != "" { t.Fatalf("playbackSeriesID = %q, want empty after episode start", m.playbackSeriesID) } - if m.playbackLibraryID != "" { - t.Fatalf("playbackLibraryID = %q, want empty after episode start", m.playbackLibraryID) + if m.playbackLibraryID != "lib-pod" { + t.Fatalf("playbackLibraryID = %q, want lib-pod, the library of the podcast", m.playbackLibraryID) } } @@ -1836,7 +1836,7 @@ func TestLoadCaptionsCmdDownloadsMatchingVTT(t *testing.T) { })) defer srv.Close() - cmd := loadCaptionsCmd(cache.NewClient(abs.NewClient(srv.URL, "tok"), nil), "item-001", "book.m4b", "vtt-1", 7) + cmd := loadCaptionsCmd(cache.NewClient(abs.NewClient(srv.URL, "tok"), nil), "item-001", "book.m4b", "vtt-1", true, 7) msg := cmd() loaded, ok := msg.(CaptionLoadedMsg) if !ok { @@ -1862,7 +1862,7 @@ func TestLoadCaptionsCmdNoSidecar(t *testing.T) { })) defer srv.Close() - msg := loadCaptionsCmd(cache.NewClient(abs.NewClient(srv.URL, "tok"), nil), "item-001", "book.m4b", "", 1)() + msg := loadCaptionsCmd(cache.NewClient(abs.NewClient(srv.URL, "tok"), nil), "item-001", "book.m4b", "", false, 1)() loaded, ok := msg.(CaptionLoadedMsg) if !ok { t.Fatalf("got %T", msg) @@ -2026,3 +2026,273 @@ func TestBuildVersion(t *testing.T) { } } } + +// TestBuildBookPlaySessionMsgAtEndOfBookSelectsLastTrack verifies that the +// position of the end of a book plays the end of the last track. handleSeek +// gives that position for a seek forward near the end of the book. +func TestBuildBookPlaySessionMsgAtEndOfBookSelectsLastTrack(t *testing.T) { + client := cache.NewClient(abs.NewClient("http://test", "tok"), nil) + session := &abs.PlaySession{ + ID: "sess", + AudioTracks: []abs.AudioTrack{ + {Index: 0, StartOffset: 0, ContentURL: "/s/track0.mp3", Duration: 1800}, + {Index: 1, StartOffset: 1800, ContentURL: "/s/track1.mp3", Duration: 1800}, + }, + } + msg, err := buildBookPlaySessionMsg(client, session, "item-001", "Title", nil, 3600, 3600) + if err != nil { + t.Fatalf("buildBookPlaySessionMsg: %v", err) + } + if msg.StreamURL != "http://test/s/track1.mp3" { + t.Errorf("StreamURL = %q, want the last track", msg.StreamURL) + } + if msg.Session.TrackStartOffset != 1800 || msg.Session.CurrentTime != 1800 { + t.Errorf("track start = %v, seek time = %v; want 1800, 1800 (the end of the last track)", msg.Session.TrackStartOffset, msg.Session.CurrentTime) + } +} + +// TestSeekToEndOfEpisodeSeeksPlayer verifies that a seek forward near the end +// of a podcast episode seeks the player. An episode has one track, so the seek +// must not start a new session. +func TestSeekToEndOfEpisodeSeeksPlayer(t *testing.T) { + log, client := newFakeABS(t, nil, nil) + mp := &mockPlayer{position: 990, duration: 1000} + m := NewWithPlayer(config.Default(), nil, client, nil, mp) + m.sessionID = "sess-ep" + m.itemID = "pod-001" + m.episodeID = "ep-001" + m.player.Playing = true + m.player.Position = 990 + m.player.Duration = 1000 + m.trackDuration = 1000 + + m, cmd := m.handleSeek(30) + m, _ = feedCmdWithin(m, cmd, slowCmdWait) + + if m.sessionID != "sess-ep" { + t.Errorf("sessionID = %q, want sess-ep: the seek restarted the playback", m.sessionID) + } + if n := len(requestsTo(log, http.MethodPost, "/api/items/pod-001/play")); n != 0 { + t.Errorf("the seek sent %d book play requests for the podcast", n) + } + if pos, _ := mp.GetPosition(); pos != 1000 { + t.Errorf("player position = %v, want 1000", pos) + } +} + +// TestSyncTickOfEarlierPlaybackEndsItsChain verifies that a sync tick of an +// earlier playback sends nothing and starts no tick. Each playback starts its +// own ticks, so the ticks of an earlier playback must end. +func TestSyncTickOfEarlierPlaybackEndsItsChain(t *testing.T) { + const syncPath = "/api/session/sess-abc/sync" + log, client := newFakeABS(t, nil, nil) + m := newSyncTestModel(client) + m.playGeneration = 2 + m = listen(m, 110) + + result, cmd := m.Update(SyncTickMsg{Generation: 1}) + if cmd != nil { + t.Error("the sync tick of an earlier playback returned a command") + } + feedCmd(result.(Model), cmd) + if n := len(requestsTo(log, http.MethodPost, syncPath)); n != 0 { + t.Errorf("the sync tick of an earlier playback sent %d syncs", n) + } +} + +// newTestCacheStore returns a cache store in a new database file. +func newTestCacheStore(t *testing.T) *cache.Store { + t.Helper() + dbStore, err := db.Open(t.TempDir() + "/cache.db") + if err != nil { + t.Fatalf("failed to open test db: %v", err) + } + t.Cleanup(func() { _ = dbStore.Close() }) + return cache.NewStore(dbStore) +} + +// TestPlaybackSwitchEvictsCachesOfPlayingItem verifies that the start of +// another book or episode evicts the cached series and home shelves of the +// item that played, not those of the new item. +func TestPlaybackSwitchEvictsCachesOfPlayingItem(t *testing.T) { + book := testLibraryItem("book-b", "Book B") + book.LibraryID = "lib-b" + book.Media.Metadata.Series = &abs.SeriesSequence{ID: "series-b", Name: "Series B", Sequence: "1"} + podcast := testPodcastItem("pod-001", "A Podcast") + podcast.LibraryID = "lib-pod" + + tests := []struct { + name string + start func(Model) (Model, tea.Cmd) + }{ + {"book", func(m Model) (Model, tea.Cmd) { + return m.handlePlayCmd(detail.PlayCmd{Item: book}) + }}, + {"episode", func(m Model) (Model, tea.Cmd) { + return m.handlePlayEpisodeCmd(detail.PlayEpisodeCmd{Item: podcast, Episode: podcast.Media.Episodes[0]}) + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, client := newFakeABS(t, nil, nil) + cacheStore := newTestCacheStore(t) + seedCache(t, cacheStore, cache.SeriesContentsKey("series-a"), &abs.SeriesContents{}) + seedCache(t, cacheStore, cache.PersonalizedKey("lib-a"), []abs.PersonalizedResponse{}) + + m := NewWithPlayer(config.Default(), nil, client, cacheStore, &mockPlayer{}) + m.sessionID = "sess-a" + m.itemID = "book-a" + m.playbackSeriesID = "series-a" + m.playbackLibraryID = "lib-a" + + m, cmd := tt.start(m) + feedCmdWithin(m, cmd, slowCmdWait) + + assertEvicted[abs.SeriesContents](t, cacheStore, cache.SeriesContentsKey("series-a")) + assertEvicted[[]abs.PersonalizedResponse](t, cacheStore, cache.PersonalizedKey("lib-a")) + }) + } +} + +// TestStopEvictsHomeShelvesOfItemWithoutSeries verifies that the stop of a +// book with no series, or of a podcast episode, evicts the cached home shelves +// of its library. The shelves show the progress of the item. +func TestStopEvictsHomeShelvesOfItemWithoutSeries(t *testing.T) { + book := testLibraryItem("book-001", "A Book") + book.LibraryID = "lib-books" + podcast := testPodcastItem("pod-001", "A Podcast") + podcast.LibraryID = "lib-pods" + session := abs.PlaySession{ + ID: "sess-new", + AudioTracks: []abs.AudioTrack{{ContentURL: "/s/audio.mp3", Duration: 1800}}, + } + + tests := []struct { + name string + libraryID string + start func(Model) (Model, tea.Cmd) + }{ + {"book", "lib-books", func(m Model) (Model, tea.Cmd) { + return m.handlePlayCmd(detail.PlayCmd{Item: book}) + }}, + {"episode", "lib-pods", func(m Model) (Model, tea.Cmd) { + return m.handlePlayEpisodeCmd(detail.PlayEpisodeCmd{Item: podcast, Episode: podcast.Media.Episodes[0]}) + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, client := newFakeABS(t, map[string]abs.PlaySession{ + "/api/items/book-001/play": session, + "/api/items/pod-001/play/pod-001-ep-001": session, + }, nil) + cacheStore := newTestCacheStore(t) + m := NewWithPlayer(config.Default(), nil, client, cacheStore, &mockPlayer{}) + + m, cmd := tt.start(m) + m, _ = feedCmdWithin(m, cmd, slowCmdWait) + if !m.isPlaying() { + t.Fatal("the playback did not start") + } + seedCache(t, cacheStore, cache.PersonalizedKey(tt.libraryID), []abs.PersonalizedResponse{}) + + m, cmd = m.stopPlayback() + feedCmdWithin(m, cmd, slowCmdWait) + + assertEvicted[[]abs.PersonalizedResponse](t, cacheStore, cache.PersonalizedKey(tt.libraryID)) + }) + } +} + +// TestPlaybackStartWithSessionFilesFetchesNoFiles verifies that the start of +// a session that gives the files of the item fetches no file list for the +// captions. The session has no VTT file, so the item has none. +func TestPlaybackStartWithSessionFilesFetchesNoFiles(t *testing.T) { + session := abs.PlaySession{ + ID: "sess-new", + AudioTracks: []abs.AudioTrack{ + {ContentURL: "/s/book.m4b", Duration: 3600, Metadata: abs.FileMetadata{Filename: "book.m4b"}}, + }, + LibraryItem: abs.PlaySessionItem{ + LibraryFiles: []abs.LibraryFile{{Ino: "audio-1", Metadata: abs.FileMetadata{Filename: "book.m4b"}}}, + }, + } + log, client := newFakeABS(t, map[string]abs.PlaySession{"/api/items/book-001/play": session}, nil) + m := NewWithPlayer(config.Default(), nil, client, nil, &mockPlayer{}) + + m, cmd := m.handlePlayCmd(detail.PlayCmd{Item: testLibraryItem("book-001", "A Book")}) + m, cmd = feedCmdWithin(m, cmd, slowCmdWait) + if !m.isPlaying() { + t.Fatal("the playback did not start") + } + feedCmdWithin(m, cmd, slowCmdWait) + + if n := len(requestsTo(log, http.MethodGet, "/api/items/book-001")); n != 0 { + t.Errorf("the start fetched the item %d times for its files", n) + } +} + +// TestRestoreSkippedAfterPlayRequest verifies that the restore at the start +// does nothing after a play request of the user: the request of the user +// stays, with its series. +func TestRestoreSkippedAfterPlayRequest(t *testing.T) { + m := newPlaybackTestModel() + result, cmd := m.Update(detail.PlayCmd{Item: abs.LibraryItem{ + ID: "item-b", + LibraryID: "lib-1", + MediaType: "book", + Media: abs.Media{Metadata: abs.MediaMetadata{Series: &abs.SeriesSequence{ID: "series-b"}}}, + }}) + m = result.(Model) + if cmd == nil { + t.Fatal("PlayCmd returns no play request") + } + + result, cmd = m.Update(RestoreSessionMsg{Item: &abs.LibraryItem{ + ID: "item-a", + LibraryID: "lib-1", + MediaType: "book", + Media: abs.Media{Metadata: abs.MediaMetadata{Series: &abs.SeriesSequence{ID: "series-a"}}}, + }}) + m = result.(Model) + if cmd != nil { + t.Error("the restore starts a playback after a play request") + } + if m.playbackSeriesID != "series-b" { + t.Errorf("playbackSeriesID = %q, want series-b", m.playbackSeriesID) + } +} + +// TestRestoredSessionClosedWhilePlaying verifies that a restored session that +// comes while an item plays does not replace the playback. pine closes the +// restored session. +func TestRestoredSessionClosedWhilePlaying(t *testing.T) { + log := &apiLog{} + srv := newMockABSServer(log) + defer srv.Close() + client := abs.NewClient(srv.URL, "tok") + m := NewWithPlayer(config.Default(), nil, cache.NewClient(client, nil), nil, &mockPlayer{}) + result, _ := m.Update(PlaySessionMsg{Session: PlaySessionData{SessionID: "sess-b", ItemID: "item-b", Duration: 3600, TrackDuration: 3600}}) + m = result.(Model) + + result, cmd := m.Update(RestorePlaySessionMsg{PlaySessionMsg: PlaySessionMsg{Session: PlaySessionData{ + SessionID: "sess-a", + ItemID: "item-a", + Duration: 3600, + TrackDuration: 3600, + }}}) + m = result.(Model) + if m.sessionID != "sess-b" || m.itemID != "item-b" { + t.Errorf("session = %q, item = %q, want sess-b and item-b", m.sessionID, m.itemID) + } + + if cmd == nil { + t.Fatal("pine does not close the restored session") + } + cmd() + if log.count(http.MethodPost, "/api/session/sess-a/close") != 1 { + t.Errorf("requests = %v, want one close of sess-a", summarizeRequests(log.get())) + } + if log.count(http.MethodPost, "/api/session/sess-b/close") != 0 { + t.Error("pine closed the session of the playback") + } +} diff --git a/internal/app/progress_sync_test.go b/internal/app/progress_sync_test.go index 9305587..ab16496 100644 --- a/internal/app/progress_sync_test.go +++ b/internal/app/progress_sync_test.go @@ -72,7 +72,7 @@ func timesListened(log *apiLog, path string) []float64 { // syncTick runs one sync tick and its commands. func syncTick(m Model) Model { - result, cmd := m.Update(SyncTickMsg{}) + result, cmd := m.Update(SyncTickMsg{Generation: m.playGeneration}) m, _ = feedCmd(result.(Model), cmd) return m } @@ -409,6 +409,29 @@ func TestMarkFinishedSendsExplicitFlag(t *testing.T) { } } +// TestMarkFinishedOfEpisodeNamesTheEpisode verifies that the result of a mark +// of an episode names the episode, so that the detail screen keeps it out of +// the progress of the podcast. +func TestMarkFinishedOfEpisodeNamesTheEpisode(t *testing.T) { + for _, undo := range []bool{false, true} { + _, client := newFakeABS(t, nil, nil) + m := newSyncTestModel(client) + + _, cmd := m.handleMarkFinished(detail.MarkFinishedCmd{ + Item: testLibraryItem("pod-001", "A Podcast"), + Episode: &abs.PodcastEpisode{ID: "ep-001", Duration: 600}, + Undo: undo, + }) + msg, ok := cmd().(detail.MarkFinishedMsg) + if !ok { + t.Fatalf("undo=%v: expected MarkFinishedMsg", undo) + } + if msg.EpisodeID != "ep-001" { + t.Errorf("undo=%v: EpisodeID = %q, want ep-001", undo, msg.EpisodeID) + } + } +} + // TestStopOfUntouchedSessionSendsNoProgress verifies that the stop of a // session sends no position if the user listened to nothing and did not move // the position. pine restores the last session at each start. For a finished diff --git a/internal/cache/client.go b/internal/cache/client.go index 550f616..5002752 100644 --- a/internal/cache/client.go +++ b/internal/cache/client.go @@ -2,6 +2,7 @@ package cache import ( "context" + "sync" "time" "github.com/Thelost77/pine/internal/abs" @@ -24,6 +25,14 @@ type Client struct { *abs.Client store *Store OnInvalidate func() + + // generation counts the calls of invalidate. cached does not store the + // value of a fetch that started in an earlier generation, because the + // value can be from before the change. invalidate holds mu while it + // clears the store, and cached holds it while it checks the generation + // and stores the value, so no old value comes after the clear. + mu sync.RWMutex + generation uint64 } // NewClient creates a caching wrapper around the given ABS client. @@ -52,10 +61,18 @@ func cached[T any](c *Client, key string, ttl time.Duration, fetch func() (T, er return v, nil } + c.mu.RLock() + generation := c.generation + c.mu.RUnlock() v, err := fetch() if err != nil { return v, err } + c.mu.RLock() + defer c.mu.RUnlock() + if c.generation != generation { + return v, nil + } if err := c.store.Put(key, v, ttl); err != nil { logger.Warn("cache write failed", "key", key, "err", err) } @@ -124,10 +141,11 @@ func (c *Client) GetSeriesContents(ctx context.Context, libraryID, seriesID stri } // FilterAudioLibraries filters audio libraries using cache or fetches from the API. -func (c *Client) FilterAudioLibraries(ctx context.Context, libs []abs.Library) ([]abs.Library, error) { - return cached(c, filteredLibrariesKey, ttlLibraries, func() ([]abs.Library, error) { - return c.Client.FilterAudioLibraries(ctx, libs) +func (c *Client) FilterAudioLibraries(ctx context.Context, libs []abs.Library) []abs.Library { + v, _ := cached(c, filteredLibrariesKey, ttlLibraries, func() ([]abs.Library, error) { + return c.Client.FilterAudioLibraries(ctx, libs), nil }) + return v } // GetBookmarks returns bookmarks from cache or fetches from the API. @@ -141,11 +159,13 @@ func (c *Client) GetBookmarks(ctx context.Context, itemID string) ([]abs.Bookmar // tells the in-memory caches (the search cache) to drop their snapshots. A // change is rare, so it clears each key. func (c *Client) invalidate() { - if c.store == nil { - return - } - if err := c.store.ClearAll(); err != nil { - logger.Warn("cache clear failed", "err", err) + if c.store != nil { + c.mu.Lock() + c.generation++ + if err := c.store.ClearAll(); err != nil { + logger.Warn("cache clear failed", "err", err) + } + c.mu.Unlock() } if c.OnInvalidate != nil { c.OnInvalidate() diff --git a/internal/cache/client_test.go b/internal/cache/client_test.go index 214fdf9..8af07cb 100644 --- a/internal/cache/client_test.go +++ b/internal/cache/client_test.go @@ -424,3 +424,72 @@ func TestClient_InvalidationClearsCache(t *testing.T) { }) } } + +// TestClient_InvalidationWithNilStoreTellsTheInMemoryCaches verifies that a +// client with no store still tells the search cache about a change. +func TestClient_InvalidationWithNilStoreTellsTheInMemoryCaches(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + client := NewClient(abs.NewClient(srv.URL, "tok"), nil) + invalidated := false + client.OnInvalidate = func() { invalidated = true } + if err := client.DeleteItem(context.Background(), "li1", false); err != nil { + t.Fatalf("DeleteItem error: %v", err) + } + if !invalidated { + t.Error("DeleteItem did not call OnInvalidate") + } +} + +// TestClient_FetchThatEndsAfterAnInvalidationIsNotCached verifies that a +// fetch that started before a change on the server does not put its old +// value in the cache after the change cleared it. +func TestClient_FetchThatEndsAfterAnInvalidationIsNotCached(t *testing.T) { + var title atomic.Value + title.Store("old") + started := make(chan struct{}) + release := make(chan struct{}) + var held atomic.Bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete { + title.Store("new") + w.WriteHeader(http.StatusOK) + return + } + body := `{"id":"li1","media":{"metadata":{"title":"` + title.Load().(string) + `"}}}` + if held.CompareAndSwap(false, true) { + close(started) + <-release + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + })) + defer srv.Close() + + client := NewClient(abs.NewClient(srv.URL, "tok"), NewStore(openTestDB(t))) + ctx := context.Background() + done := make(chan error, 1) + go func() { + _, err := client.GetLibraryItem(ctx, "li1") + done <- err + }() + <-started + if err := client.DeleteItem(ctx, "li1", false); err != nil { + t.Fatalf("DeleteItem error: %v", err) + } + close(release) + if err := <-done; err != nil { + t.Fatalf("first GetLibraryItem error: %v", err) + } + + item, err := client.GetLibraryItem(ctx, "li1") + if err != nil { + t.Fatalf("second GetLibraryItem error: %v", err) + } + if got := item.Media.Metadata.Title; got != "new" { + t.Errorf("title after the change = %q, want new", got) + } +} diff --git a/internal/captions/vtt.go b/internal/captions/vtt.go index ce14e1b..7be7ccb 100644 --- a/internal/captions/vtt.go +++ b/internal/captions/vtt.go @@ -4,6 +4,7 @@ package captions import ( "bytes" "html" + "math" "strconv" "strings" "unicode" @@ -30,7 +31,8 @@ func ParseVTT(data []byte) []Cue { } if i < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[i]), "WEBVTT") { i++ - for i < len(lines) && strings.TrimSpace(lines[i]) != "" { + // A timing line ends the header also with no blank line before it. + for i < len(lines) && strings.TrimSpace(lines[i]) != "" && !strings.Contains(lines[i], "-->") { i++ } } @@ -153,6 +155,10 @@ func parseTimestamp(s string) (float64, error) { default: return 0, strconv.ErrSyntax } + // ParseFloat accepts "inf" and "NaN", and Atoi accepts a sign. + if hours < 0 || minutes < 0 || seconds < 0 || math.IsNaN(seconds) || math.IsInf(seconds, 0) { + return 0, strconv.ErrSyntax + } return float64(hours)*3600 + float64(minutes)*60 + seconds, nil } @@ -163,7 +169,7 @@ func stripTags(s string) string { switch { case r == '<': inTag = true - case r == '>': + case r == '>' && inTag: inTag = false case !inTag: b.WriteRune(r) diff --git a/internal/captions/vtt_test.go b/internal/captions/vtt_test.go index e2cd342..30e993d 100644 --- a/internal/captions/vtt_test.go +++ b/internal/captions/vtt_test.go @@ -1,6 +1,8 @@ package captions import ( + "reflect" + "strings" "testing" ) @@ -84,6 +86,53 @@ func TestParseVTTDecodesEntitiesAndStripsControls(t *testing.T) { } } +func TestParseVTTHeaderForms(t *testing.T) { + cues := "00:00:01.000 --> 00:00:02.000\nFirst\n\n00:00:03.000 --> 00:00:04.000\nSecond\n" + for _, test := range []struct { + name string + data string + }{ + {"no blank line after the header", "WEBVTT\n" + cues}, + {"header lines", "WEBVTT\nKind: captions\nLanguage: en\n\n" + cues}, + {"byte order mark and CRLF", "\xEF\xBB\xBFWEBVTT\r\n\r\n" + strings.ReplaceAll(cues, "\n", "\r\n")}, + } { + t.Run(test.name, func(t *testing.T) { + got := ParseVTT([]byte(test.data)) + want := []Cue{{Start: 1, End: 2, Text: "First"}, {Start: 3, End: 4, Text: "Second"}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("ParseVTT() = %+v, want %+v", got, want) + } + }) + } +} + +func TestParseVTTKeepsAGreaterThanSignOutsideATag(t *testing.T) { + data := []byte("WEBVTT\n\n00:00:01.000 --> 00:00:02.000\n5 > 3 and x -> y\n") + + cues := ParseVTT(data) + if len(cues) != 1 || cues[0].Text != "5 > 3 and x -> y" { + t.Fatalf("ParseVTT() = %+v, want one cue with the text %q", cues, "5 > 3 and x -> y") + } +} + +func TestParseVTTSkipsCuesWithTimesThatAreNotFiniteOrNegative(t *testing.T) { + data := []byte("WEBVTT\n\n" + + "00:00:00.000 --> 00:00:inf\nInfinite\n\n" + + "00:00:00.000 --> 00:00:NaN\nNot a number\n\n" + + "-1:00.000 --> 00:01.000\nNegative\n\n" + + "01:-5:00.000 --> 01:00:00.000\nNegative minutes\n\n" + + "00:00:05.000 --> 00:00:06.000\nValid\n") + + cues := ParseVTT(data) + want := []Cue{{Start: 5, End: 6, Text: "Valid"}} + if !reflect.DeepEqual(cues, want) { + t.Fatalf("ParseVTT() = %+v, want %+v", cues, want) + } + if got := At(cues, 5.5); got != "Valid" { + t.Errorf("At(5.5) = %q, want Valid", got) + } +} + func containsRune(s string, r rune) bool { for _, c := range s { if c == r { diff --git a/internal/config/config.go b/internal/config/config.go index 2ef6f1d..c0a83cd 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "errors" "fmt" + "math" "os" "path/filepath" "strings" @@ -15,6 +16,13 @@ import ( "github.com/Thelost77/pine/internal/ui" ) +// The limits of player.speed. mpv does not accept a speed above 100, and the +// speed-down key stops at 0.1. +const ( + minSpeed = 0.1 + maxSpeed = 100 +) + type PlayerConfig struct { Speed float64 `toml:"speed"` SeekSeconds int `toml:"seek_seconds"` @@ -90,6 +98,12 @@ func Load(path string) (Config, error) { if err != nil { return Config{}, err } + if s := cfg.Player.Speed; math.IsNaN(s) || s < minSpeed || s > maxSpeed { + return Config{}, fmt.Errorf("player.speed is %v: it must be from %v to %v", s, minSpeed, maxSpeed) + } + if cfg.Player.SeekSeconds <= 0 { + return Config{}, fmt.Errorf("player.seek_seconds is %d: it must be more than 0", cfg.Player.SeekSeconds) + } changed, err := ensurePlaybackIdentity(&cfg) if err != nil { return Config{}, fmt.Errorf("generate playback device identity: %w", err) @@ -104,6 +118,9 @@ func Load(path string) (Config, error) { } func saveMigratedPlaybackIdentity(path string, data []byte, cfg Config) error { + // TOML allows a byte order mark only at the start of the file, and the + // identity comes before data. + data = bytes.TrimPrefix(data, []byte("\xEF\xBB\xBF")) var identity bytes.Buffer if err := toml.NewEncoder(&identity).Encode(struct { DeviceName string `toml:"device_name"` @@ -163,13 +180,17 @@ func withoutTopLevelIdentity(data []byte) []byte { return result.Bytes() } +// isIdentityAssignment reports whether line sets key. The key can be bare or +// quoted. func isIdentityAssignment(line []byte, key string) bool { line = bytes.TrimLeft(line, " \t") - if !bytes.HasPrefix(line, []byte(key)) { - return false + for _, form := range []string{key, `"` + key + `"`, "'" + key + "'"} { + if rest, ok := bytes.CutPrefix(line, []byte(form)); ok { + rest = bytes.TrimLeft(rest, " \t") + return len(rest) > 0 && rest[0] == '=' + } } - line = bytes.TrimLeft(line[len(key):], " \t") - return len(line) > 0 && line[0] == '=' + return false } func defaultDeviceName() string { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index e9e3c85..c498e42 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -44,9 +44,6 @@ func TestLoadEmptyPathReturnsDefaults(t *testing.T) { if cfg.Theme.Border != "#4f585e" { t.Errorf("expected border #4f585e, got %q", cfg.Theme.Border) } - if cfg.Theme.Warning != "#dbbc7f" { - t.Errorf("expected warning #dbbc7f, got %q", cfg.Theme.Warning) - } if cfg.Theme.Info != "#7fbbb3" { t.Errorf("expected info #7fbbb3, got %q", cfg.Theme.Info) } @@ -184,6 +181,8 @@ func TestLoadUpsertsPartialPlaybackIdentity(t *testing.T) { {"name only", "# keep me\ndevice_name = \"Desk Pine\" # keep this\n[player]\nspeed = 1.5\n"}, {"ID only", "device_id = \"pine-manual\"\n[server]\naddress = \"https://abs.example\"\n"}, {"empty values", "device_name = \"\"\ndevice_id = \"\"\n"}, + {"quoted keys", "\"device_name\" = \"\"\n'device_id' = \"\"\n"}, + {"byte order mark", "\xEF\xBB\xBF[player]\nspeed = 1.5\n"}, } { t.Run(test.name, func(t *testing.T) { path := filepath.Join(t.TempDir(), "config.toml") @@ -276,6 +275,41 @@ func TestLoadInvalidTOMLReturnsError(t *testing.T) { } } +func TestLoadChecksPlayerValues(t *testing.T) { + for _, test := range []struct { + player string + wantErr string + }{ + {"speed = 0.1\nseek_seconds = 1", ""}, + {"speed = 100.0\nseek_seconds = 30", ""}, + {"speed = 0.0", "player.speed"}, + {"speed = -1.0", "player.speed"}, + {"speed = 150.0", "player.speed"}, + {"speed = nan", "player.speed"}, + {"seek_seconds = 0", "player.seek_seconds"}, + {"seek_seconds = -10", "player.seek_seconds"}, + } { + t.Run(test.player, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + data := "device_name = \"Desk Pine\"\ndevice_id = \"pine-id\"\n[player]\n" + test.player + "\n" + if err := os.WriteFile(path, []byte(data), 0600); err != nil { + t.Fatalf("write config: %v", err) + } + + _, err := Load(path) + if test.wantErr == "" { + if err != nil { + t.Fatalf("Load() error: %v", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), test.wantErr) { + t.Fatalf("Load() error = %v, want an error that names %s", err, test.wantErr) + } + }) + } +} + func TestEnsureExistsCreatesDefaultConfig(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "config.toml") diff --git a/internal/db/accounts.go b/internal/db/accounts.go index 1de3b19..f10266a 100644 --- a/internal/db/accounts.go +++ b/internal/db/accounts.go @@ -12,14 +12,12 @@ type Account struct { ServerURL string Username string Token string - IsDefault bool CreatedAt time.Time } -// SaveAccount inserts or updates an account. If it's the first account, it -// becomes the default automatically. When the saved account is (or becomes) -// the default, any other accounts are unset as default atomically within a -// transaction so that only one default can exist at a time. +// SaveAccount inserts or updates an account and makes it the default. It +// deletes each other account in the same transaction, so that the database +// keeps no token of an earlier login. func (s *Store) SaveAccount(a Account) error { tx, err := s.DB.Begin() if err != nil { @@ -27,36 +25,19 @@ func (s *Store) SaveAccount(a Account) error { } defer func() { _ = tx.Rollback() }() - // If no accounts exist yet, make this one the default. - var count int - if err := tx.QueryRow(`SELECT COUNT(*) FROM accounts`).Scan(&count); err != nil { - return fmt.Errorf("counting accounts: %w", err) - } - if count == 0 { - a.IsDefault = true - } - - isDefault := 0 - if a.IsDefault { - isDefault = 1 - } - - // Unset the default flag on all other accounts before upserting this one. - if a.IsDefault { - if _, err := tx.Exec(`UPDATE accounts SET is_default = 0 WHERE id != ?`, a.ID); err != nil { - return fmt.Errorf("unsetting other defaults: %w", err) - } + if _, err := tx.Exec(`DELETE FROM accounts WHERE id != ?`, a.ID); err != nil { + return fmt.Errorf("deleting other accounts: %w", err) } _, err = tx.Exec(` INSERT INTO accounts (id, server_url, username, token, is_default, created_at) - VALUES (?, ?, ?, ?, ?, COALESCE((SELECT created_at FROM accounts WHERE id = ?), datetime('now'))) + VALUES (?, ?, ?, ?, 1, COALESCE((SELECT created_at FROM accounts WHERE id = ?), datetime('now'))) ON CONFLICT(id) DO UPDATE SET server_url = excluded.server_url, username = excluded.username, token = excluded.token, is_default = excluded.is_default - `, a.ID, a.ServerURL, a.Username, a.Token, isDefault, a.ID) + `, a.ID, a.ServerURL, a.Username, a.Token, a.ID) if err != nil { return fmt.Errorf("saving account: %w", err) } @@ -68,10 +49,11 @@ func (s *Store) SaveAccount(a Account) error { } // GetDefaultAccount returns the account marked as default. -// Returns an error if no default account is set. +// Returns an error if no default account is set. A database of an earlier +// pine can have more accounts, which are not the default. func (s *Store) GetDefaultAccount() (Account, error) { row := s.DB.QueryRow(` - SELECT id, server_url, username, token, is_default, created_at + SELECT id, server_url, username, token, created_at FROM accounts WHERE is_default = 1 LIMIT 1 `) return scanAccount(row) @@ -80,13 +62,11 @@ func (s *Store) GetDefaultAccount() (Account, error) { // scanAccount scans a single account from a *sql.Row. func scanAccount(row *sql.Row) (Account, error) { var a Account - var isDefault int var createdAt string - err := row.Scan(&a.ID, &a.ServerURL, &a.Username, &a.Token, &isDefault, &createdAt) + err := row.Scan(&a.ID, &a.ServerURL, &a.Username, &a.Token, &createdAt) if err != nil { return Account{}, fmt.Errorf("scanning account: %w", err) } - a.IsDefault = isDefault == 1 a.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt) return a, nil } diff --git a/internal/db/accounts_test.go b/internal/db/accounts_test.go index 759a257..d9fcb9d 100644 --- a/internal/db/accounts_test.go +++ b/internal/db/accounts_test.go @@ -24,7 +24,6 @@ func TestSaveAccount_Insert(t *testing.T) { ServerURL: "http://localhost:13378", Username: "admin", Token: "tok-abc", - IsDefault: true, } if err := s.SaveAccount(acc); err != nil { @@ -47,9 +46,6 @@ func TestSaveAccount_Insert(t *testing.T) { if got.Token != acc.Token { t.Errorf("Token = %q, want %q", got.Token, acc.Token) } - if !got.IsDefault { - t.Error("IsDefault = false, want true") - } if got.CreatedAt.IsZero() { t.Error("CreatedAt should not be zero") } @@ -63,7 +59,6 @@ func TestSaveAccount_Upsert(t *testing.T) { ServerURL: "http://old.server", Username: "admin", Token: "tok-old", - IsDefault: true, } if err := s.SaveAccount(acc); err != nil { t.Fatalf("first SaveAccount() error: %v", err) @@ -99,7 +94,6 @@ func TestGetDefaultAccount_NoDefault(t *testing.T) { func TestSaveAccount_FirstAccountBecomesDefault(t *testing.T) { s := openTestStore(t) - // Save without explicitly setting IsDefault acc := Account{ID: "a1", ServerURL: "http://s", Username: "u", Token: "t"} if err := s.SaveAccount(acc); err != nil { t.Fatal(err) @@ -114,40 +108,27 @@ func TestSaveAccount_FirstAccountBecomesDefault(t *testing.T) { } } -func TestSaveAccount_UnsetsOtherDefault(t *testing.T) { +// TestSaveAccount_DeletesOtherAccounts verifies that the database keeps no +// token of an earlier login. +func TestSaveAccount_DeletesOtherAccounts(t *testing.T) { s := openTestStore(t) - acc1 := Account{ID: "a1", ServerURL: "http://s1", Username: "u1", Token: "t1", IsDefault: true} - if err := s.SaveAccount(acc1); err != nil { + if err := s.SaveAccount(Account{ID: "a1", ServerURL: "http://s1", Username: "u1", Token: "t1"}); err != nil { t.Fatalf("first SaveAccount() error: %v", err) } - - acc2 := Account{ID: "a2", ServerURL: "http://s2", Username: "u2", Token: "t2", IsDefault: true} - if err := s.SaveAccount(acc2); err != nil { + if err := s.SaveAccount(Account{ID: "a2", ServerURL: "http://s2", Username: "u2", Token: "t2"}); err != nil { t.Fatalf("second SaveAccount() error: %v", err) } - var isDefault1 int - if err := s.DB.QueryRow(`SELECT is_default FROM accounts WHERE id = ?`, "a1").Scan(&isDefault1); err != nil { - t.Fatalf("querying a1: %v", err) - } - if isDefault1 != 0 { - t.Errorf("a1 is_default = %d, want 0", isDefault1) - } - - var isDefault2 int - if err := s.DB.QueryRow(`SELECT is_default FROM accounts WHERE id = ?`, "a2").Scan(&isDefault2); err != nil { - t.Fatalf("querying a2: %v", err) + var count int + if err := s.DB.QueryRow(`SELECT COUNT(*) FROM accounts`).Scan(&count); err != nil { + t.Fatalf("count accounts: %v", err) } - if isDefault2 != 1 { - t.Errorf("a2 is_default = %d, want 1", isDefault2) + if count != 1 { + t.Errorf("accounts table has %d rows, want 1", count) } - got, err := s.GetDefaultAccount() - if err != nil { - t.Fatalf("GetDefaultAccount() error: %v", err) - } - if got.ID != "a2" { - t.Errorf("default ID = %q, want %q", got.ID, "a2") + if err != nil || got.ID != "a2" { + t.Fatalf("GetDefaultAccount() = %+v, %v; want a2", got, err) } } diff --git a/internal/db/db_test.go b/internal/db/db_test.go index 53ef090..d7b0dd2 100644 --- a/internal/db/db_test.go +++ b/internal/db/db_test.go @@ -1,9 +1,11 @@ package db import ( + "database/sql" "os" "path/filepath" "runtime" + "strconv" "sync" "testing" ) @@ -104,6 +106,52 @@ func TestOpen_ClearsObfuscatedAccountTokens(t *testing.T) { } } +// TestOpen_MigratesLegacySchema verifies that Open updates the database of +// an old pine: its accounts table has the column token_encrypted, and its +// sessions table has no column episode_id. +func TestOpen_MigratesLegacySchema(t *testing.T) { + path := filepath.Join(t.TempDir(), "test.db") + legacy, err := sql.Open("sqlite", path) + if err != nil { + t.Fatalf("open legacy database: %v", err) + } + for _, query := range []string{ + `CREATE TABLE accounts (id TEXT PRIMARY KEY, server_url TEXT NOT NULL, username TEXT NOT NULL, token_encrypted TEXT NOT NULL, is_default INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL)`, + `CREATE TABLE sessions (id TEXT PRIMARY KEY, item_id TEXT NOT NULL, session_id TEXT NOT NULL, current_time REAL NOT NULL DEFAULT 0, duration REAL NOT NULL DEFAULT 0, created_at TEXT NOT NULL)`, + `INSERT INTO accounts VALUES ('a1', 'http://s', 'u', 'tok', 1, datetime('now'))`, + `INSERT INTO sessions VALUES ('last', 'item-1', 'sess-1', 10, 100, datetime('now'))`, + } { + if _, err := legacy.Exec(query); err != nil { + t.Fatalf("make legacy schema: %v", err) + } + } + if err := legacy.Close(); err != nil { + t.Fatalf("close legacy database: %v", err) + } + + store, err := Open(path) + if err != nil { + t.Fatalf("Open() error: %v", err) + } + defer func() { _ = store.Close() }() + + account, err := store.GetDefaultAccount() + if err != nil || account.ID != "a1" || account.Token != "tok" { + t.Fatalf("GetDefaultAccount() = %+v, %v; want a1 with the token tok", account, err) + } + last, err := store.GetLastSession() + if err != nil || last.ItemID != "item-1" || last.EpisodeID != "" { + t.Fatalf("GetLastSession() = %+v, %v; want item-1 with no episode", last, err) + } + if err := store.SaveListeningSession(ListeningSession{ItemID: "pod-1", EpisodeID: "ep-1"}); err != nil { + t.Fatalf("SaveListeningSession() error: %v", err) + } + last, err = store.GetLastSession() + if err != nil || last.ItemID != "pod-1" || last.EpisodeID != "ep-1" { + t.Fatalf("GetLastSession() after save = %+v, %v; want pod-1 and ep-1", last, err) + } +} + func TestOpen_CreatesFile(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "sub", "test.db") @@ -140,7 +188,7 @@ func TestOpen_ParallelWritesWait(t *testing.T) { wg.Add(1) go func(i int) { defer wg.Done() - errs <- s.SaveListeningSession(ListeningSession{ItemID: "item", SessionID: "session", CurrentTime: float64(i)}) + errs <- s.SaveListeningSession(ListeningSession{ItemID: "item-" + strconv.Itoa(i)}) }(i) } wg.Wait() diff --git a/internal/db/sessions.go b/internal/db/sessions.go index 97615fe..72a6b8d 100644 --- a/internal/db/sessions.go +++ b/internal/db/sessions.go @@ -3,27 +3,25 @@ package db import ( "database/sql" "fmt" - "time" ) -// ListeningSession represents the last active playback state for crash recovery. +// ListeningSession is the item or the podcast episode that played last. At +// startup, pine loads it again at the position on the server. type ListeningSession struct { - ItemID string - EpisodeID string - SessionID string - CurrentTime float64 - Duration float64 - CreatedAt time.Time + ItemID string + EpisodeID string } const lastSessionID = "last" -// SaveListeningSession stores the current playback state. Only one session is -// kept at a time (the most recent), enabling crash recovery. +// SaveListeningSession stores the item or the episode that plays. Only one +// session is kept at a time (the most recent), enabling crash recovery. It +// stores no session ID and no position: pine does not read them, and the ID +// of a play session is a secret. func (s *Store) SaveListeningSession(session ListeningSession) error { _, err := s.DB.Exec(` INSERT INTO sessions (id, item_id, episode_id, session_id, "current_time", duration, created_at) - VALUES (?, ?, ?, ?, ?, ?, datetime('now')) + VALUES (?, ?, ?, '', 0, 0, datetime('now')) ON CONFLICT(id) DO UPDATE SET item_id = excluded.item_id, episode_id = excluded.episode_id, @@ -31,7 +29,7 @@ func (s *Store) SaveListeningSession(session ListeningSession) error { "current_time" = excluded."current_time", duration = excluded.duration, created_at = excluded.created_at - `, lastSessionID, session.ItemID, session.EpisodeID, session.SessionID, session.CurrentTime, session.Duration) + `, lastSessionID, session.ItemID, session.EpisodeID) if err != nil { return fmt.Errorf("saving listening session: %w", err) } @@ -42,18 +40,15 @@ func (s *Store) SaveListeningSession(session ListeningSession) error { // Returns an error if no session has been saved. func (s *Store) GetLastSession() (ListeningSession, error) { var ls ListeningSession - var createdAt string err := s.DB.QueryRow(` - SELECT item_id, episode_id, session_id, "current_time", duration, created_at - FROM sessions WHERE id = ? - `, lastSessionID).Scan(&ls.ItemID, &ls.EpisodeID, &ls.SessionID, &ls.CurrentTime, &ls.Duration, &createdAt) + SELECT item_id, episode_id FROM sessions WHERE id = ? + `, lastSessionID).Scan(&ls.ItemID, &ls.EpisodeID) if err == sql.ErrNoRows { return ListeningSession{}, fmt.Errorf("no saved session") } if err != nil { return ListeningSession{}, fmt.Errorf("getting last session: %w", err) } - ls.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt) return ls, nil } diff --git a/internal/db/sessions_test.go b/internal/db/sessions_test.go index 944f743..04ca3f9 100644 --- a/internal/db/sessions_test.go +++ b/internal/db/sessions_test.go @@ -7,13 +7,7 @@ import ( func TestSaveListeningSession(t *testing.T) { s := openTestStore(t) - session := ListeningSession{ - ItemID: "item-123", - EpisodeID: "", - SessionID: "sess-456", - CurrentTime: 42.5, - Duration: 3600.0, - } + session := ListeningSession{ItemID: "item-123"} if err := s.SaveListeningSession(session); err != nil { t.Fatalf("SaveListeningSession() error: %v", err) @@ -23,36 +17,15 @@ func TestSaveListeningSession(t *testing.T) { if err != nil { t.Fatalf("GetLastSession() error: %v", err) } - if got.ItemID != session.ItemID { - t.Errorf("ItemID = %q, want %q", got.ItemID, session.ItemID) - } - if got.EpisodeID != session.EpisodeID { - t.Errorf("EpisodeID = %q, want %q", got.EpisodeID, session.EpisodeID) - } - if got.SessionID != session.SessionID { - t.Errorf("SessionID = %q, want %q", got.SessionID, session.SessionID) - } - if got.CurrentTime != session.CurrentTime { - t.Errorf("CurrentTime = %f, want %f", got.CurrentTime, session.CurrentTime) - } - if got.Duration != session.Duration { - t.Errorf("Duration = %f, want %f", got.Duration, session.Duration) - } - if got.CreatedAt.IsZero() { - t.Error("CreatedAt should not be zero") + if got != session { + t.Errorf("GetLastSession() = %+v, want %+v", got, session) } } func TestSaveListeningSession_WithEpisodeID(t *testing.T) { s := openTestStore(t) - session := ListeningSession{ - ItemID: "item-123", - EpisodeID: "ep-789", - SessionID: "sess-456", - CurrentTime: 42.5, - Duration: 3600.0, - } + session := ListeningSession{ItemID: "item-123", EpisodeID: "ep-789"} if err := s.SaveListeningSession(session); err != nil { t.Fatalf("SaveListeningSession() error: %v", err) @@ -70,18 +43,8 @@ func TestSaveListeningSession_WithEpisodeID(t *testing.T) { func TestSaveListeningSession_Overwrites(t *testing.T) { s := openTestStore(t) - first := ListeningSession{ - ItemID: "item-1", - SessionID: "sess-1", - CurrentTime: 10.0, - Duration: 100.0, - } - second := ListeningSession{ - ItemID: "item-2", - SessionID: "sess-2", - CurrentTime: 20.0, - Duration: 200.0, - } + first := ListeningSession{ItemID: "item-1", EpisodeID: "ep-1"} + second := ListeningSession{ItemID: "item-2"} if err := s.SaveListeningSession(first); err != nil { t.Fatalf("first SaveListeningSession() error: %v", err) @@ -94,11 +57,8 @@ func TestSaveListeningSession_Overwrites(t *testing.T) { if err != nil { t.Fatalf("GetLastSession() error: %v", err) } - if got.ItemID != "item-2" { - t.Errorf("ItemID = %q, want %q (should be latest)", got.ItemID, "item-2") - } - if got.SessionID != "sess-2" { - t.Errorf("SessionID = %q, want %q", got.SessionID, "sess-2") + if got != second { + t.Errorf("GetLastSession() = %+v, want %+v (should be latest)", got, second) } } @@ -114,13 +74,7 @@ func TestGetLastSession_Empty(t *testing.T) { func TestClearSession(t *testing.T) { s := openTestStore(t) - session := ListeningSession{ - ItemID: "item-123", - SessionID: "sess-456", - CurrentTime: 42.5, - Duration: 3600.0, - } - if err := s.SaveListeningSession(session); err != nil { + if err := s.SaveListeningSession(ListeningSession{ItemID: "item-123"}); err != nil { t.Fatal(err) } @@ -142,31 +96,3 @@ func TestClearSession_Empty(t *testing.T) { t.Fatalf("ClearSession() on empty table error: %v", err) } } - -func TestSaveListeningSession_UpdateCurrentTime(t *testing.T) { - s := openTestStore(t) - - session := ListeningSession{ - ItemID: "item-123", - SessionID: "sess-456", - CurrentTime: 10.0, - Duration: 3600.0, - } - if err := s.SaveListeningSession(session); err != nil { - t.Fatal(err) - } - - // Save again with updated time (same session) - session.CurrentTime = 500.0 - if err := s.SaveListeningSession(session); err != nil { - t.Fatal(err) - } - - got, err := s.GetLastSession() - if err != nil { - t.Fatal(err) - } - if got.CurrentTime != 500.0 { - t.Errorf("CurrentTime = %f, want 500.0", got.CurrentTime) - } -} diff --git a/internal/logger/logger.go b/internal/logger/logger.go index ce04b6d..b6ebafa 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -11,6 +11,9 @@ import ( "sync" ) +// maxLogSize is the size above which Init renames the log to .log.old. +const maxLogSize = 5 * 1024 * 1024 + var ( instance *slog.Logger logPath string @@ -31,25 +34,30 @@ func Init(dir, name string) func() { return } - // Rotate: if log exceeds 5MB, truncate - if info, err := os.Stat(path); err == nil && info.Size() > 5*1024*1024 { - _ = os.Rename(path, path+".old") - } - - f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) + f, err := openLog(path) if err != nil { return } - _ = os.Chmod(path, 0o600) - if err := lockFile(f); err != nil { + locked := lockFile(f) == nil + // Rotate only while this process holds the lock, so that the log of a + // running instance keeps its name. Windows cannot rename an open file, + // so the file closes first. + info, err := f.Stat() + if locked && err == nil && info.Size() > maxLogSize { + _ = f.Close() + _ = os.Rename(path, path+".old") + if f, err = openLog(path); err != nil { + return + } + locked = lockFile(f) == nil + } + if !locked { _ = f.Close() path = filepath.Join(dir, fmt.Sprintf("%s-%d.log", name, os.Getpid())) logPath = path - f, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) - if err != nil { + if f, err = openLog(path); err != nil { return } - _ = os.Chmod(path, 0o600) _ = lockFile(f) } instance = slog.New(slog.NewTextHandler(f, &slog.HandlerOptions{ @@ -66,6 +74,16 @@ func Init(dir, name string) func() { return cleanup } +// openLog opens the log file at path for appending, with the mode 0600. +func openLog(path string) (*os.File, error) { + f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) + if err != nil { + return nil, err + } + _ = os.Chmod(path, 0o600) + return f, nil +} + // Get returns the logger instance. Returns a no-op logger if Init hasn't been called. func Get() *slog.Logger { if instance != nil { diff --git a/internal/logger/logger_test.go b/internal/logger/logger_test.go index 25a453f..e2dc7f8 100644 --- a/internal/logger/logger_test.go +++ b/internal/logger/logger_test.go @@ -50,3 +50,28 @@ func TestInitCreatesPrivateLogFileNamedAfterApp(t *testing.T) { t.Errorf("log directory mode = %o, want 700", perm) } } + +func TestInitRotatesALargeLog(t *testing.T) { + resetForTest(t) + dir := t.TempDir() + path := filepath.Join(dir, "pine.log") + if err := os.WriteFile(path, nil, 0o600); err != nil { + t.Fatalf("create the log file: %v", err) + } + if err := os.Truncate(path, maxLogSize+1); err != nil { + t.Fatalf("grow the log file: %v", err) + } + + closeLog := Init(dir, "pine") + defer closeLog() + + if got := Path(); got != path { + t.Errorf("Path() = %q, want %q", got, path) + } + if info, err := os.Stat(path + ".old"); err != nil || info.Size() != maxLogSize+1 { + t.Errorf("stat %s.old = %v, %v; want the previous log", path, info, err) + } + if info, err := os.Stat(path); err != nil || info.Size() != 0 { + t.Errorf("stat %s = %v, %v; want a new empty log", path, info, err) + } +} diff --git a/internal/logger/logger_unix_test.go b/internal/logger/logger_unix_test.go index 2557627..88e28a6 100644 --- a/internal/logger/logger_unix_test.go +++ b/internal/logger/logger_unix_test.go @@ -3,6 +3,7 @@ package logger import ( + "errors" "fmt" "os" "path/filepath" @@ -40,3 +41,41 @@ func TestPathReportsTheFallbackFileWhenTheLogIsLocked(t *testing.T) { t.Errorf("the fallback file does not contain the log entry: %q", data) } } + +func TestInitDoesNotRotateTheLogOfARunningInstance(t *testing.T) { + resetForTest(t) + dir := t.TempDir() + path := filepath.Join(dir, "pine.log") + // A second process of the same app holds the lock on a log file that is + // larger than the rotation size. + holder, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) + if err != nil { + t.Fatalf("open the log file: %v", err) + } + defer func() { _ = holder.Close() }() + if err := holder.Truncate(maxLogSize + 1); err != nil { + t.Fatalf("grow the log file: %v", err) + } + if err := lockFile(holder); err != nil { + t.Fatalf("lock the log file: %v", err) + } + defer unlockFile(holder) + + closeLog := Init(dir, "pine") + defer closeLog() + + want := filepath.Join(dir, fmt.Sprintf("pine-%d.log", os.Getpid())) + if got := Path(); got != want { + t.Errorf("Path() = %q, want the fallback file %q", got, want) + } + holderInfo, err := holder.Stat() + if err != nil { + t.Fatalf("stat the file of the holder: %v", err) + } + if info, err := os.Stat(path); err != nil || !os.SameFile(info, holderInfo) { + t.Errorf("%s is not the file of the holder (%v)", path, err) + } + if _, err := os.Stat(path + ".old"); !errors.Is(err, os.ErrNotExist) { + t.Errorf("Init renamed the file of the holder: stat %s.old: %v", path, err) + } +} diff --git a/internal/mpris/accessor.go b/internal/mpris/accessor.go index 39946a7..ae0bfab 100644 --- a/internal/mpris/accessor.go +++ b/internal/mpris/accessor.go @@ -14,7 +14,6 @@ type ModelAccessor interface { PlayerSpeed() float64 PlayerMinimumRate() float64 PlayerMaximumRate() float64 - QueueLength() int CanSeek() bool CanGoNext() bool CanGoPrevious() bool diff --git a/internal/mpris/adapter.go b/internal/mpris/adapter.go index cd6d0a8..2e09677 100644 --- a/internal/mpris/adapter.go +++ b/internal/mpris/adapter.go @@ -17,6 +17,17 @@ const ( StatusStopped PlaybackStatus = "Stopped" ) +// playbackStatus returns the MPRIS playback status of the app state. +func playbackStatus(a ModelAccessor) PlaybackStatus { + if a.IsPlaying() { + return StatusPlaying + } + if a.IsPaused() { + return StatusPaused + } + return StatusStopped +} + // Metadata is the metadata of the current track. type Metadata struct { TrackID dbus.ObjectPath @@ -25,15 +36,33 @@ type Metadata struct { Artist []string } +// trackMetadata returns the metadata of the current track of the app state. +// name is the app name used in track object paths. +func trackMetadata(name string, a ModelAccessor) Metadata { + title := a.CurrentTitle() + if title == "" { + return Metadata{ + TrackID: dbus.ObjectPath("/org/mpris/MediaPlayer2/TrackList/NoTrack"), + } + } + return Metadata{ + TrackID: trackPath(name, a.CurrentItemID()), + Length: time.Duration(a.PlayerDuration() * float64(time.Second)), + Title: title, + Artist: a.CurrentAuthors(), + } +} + // RootAdapter supplies the org.mpris.MediaPlayer2 interface with static values. -// Name is the app name that MPRIS clients see. +// Name is the app name that MPRIS clients see. Quit and Raise do nothing, so +// CanQuit and CanRaise are false. type RootAdapter struct { Name string } func (r RootAdapter) Raise() error { return nil } func (r RootAdapter) Quit() error { return nil } -func (r RootAdapter) CanQuit() (bool, error) { return true, nil } +func (r RootAdapter) CanQuit() (bool, error) { return false, nil } func (r RootAdapter) CanRaise() (bool, error) { return false, nil } func (r RootAdapter) HasTrackList() (bool, error) { return false, nil } func (r RootAdapter) Identity() (string, error) { return r.Name, nil } @@ -41,129 +70,13 @@ func (r RootAdapter) SupportedUriSchemes() ([]string, error) { return nil, nil } func (r RootAdapter) SupportedMimeTypes() ([]string, error) { return nil, nil } func (r RootAdapter) DesktopEntry() (string, error) { return r.Name, nil } -// PlayerAdapter supplies the org.mpris.MediaPlayer2.Player interface using closures. -// Each method field is a closure that reads from a ModelAccessor. -type PlayerAdapter struct { - OnNext func() error - OnPrevious func() error - OnPause func() error - OnPlayPause func() error - OnStop func() error - OnPlay func() error - OnSeek func(offset time.Duration) error - OnSetPosition func(trackId string, position time.Duration) error - OnOpenUri func(uri string) error - OnPlaybackStatus func() (PlaybackStatus, error) - OnRate func() (float64, error) - OnSetRate func(rate float64) error - OnMetadata func() (Metadata, error) - OnVolume func() (float64, error) - OnSetVolume func(vol float64) error - OnPosition func() (int64, error) - OnMinimumRate func() (float64, error) - OnMaximumRate func() (float64, error) - OnCanGoNext func() (bool, error) - OnCanGoPrevious func() (bool, error) - OnCanPlay func() (bool, error) - OnCanPause func() (bool, error) - OnCanSeek func() (bool, error) - OnCanControl func() (bool, error) -} - -func (p PlayerAdapter) Next() error { return p.OnNext() } -func (p PlayerAdapter) Previous() error { return p.OnPrevious() } -func (p PlayerAdapter) Pause() error { return p.OnPause() } -func (p PlayerAdapter) PlayPause() error { return p.OnPlayPause() } -func (p PlayerAdapter) Stop() error { return p.OnStop() } -func (p PlayerAdapter) Play() error { return p.OnPlay() } -func (p PlayerAdapter) Seek(offset time.Duration) error { return p.OnSeek(offset) } -func (p PlayerAdapter) SetPosition(trackId string, position time.Duration) error { - return p.OnSetPosition(trackId, position) -} -func (p PlayerAdapter) OpenUri(uri string) error { return p.OnOpenUri(uri) } -func (p PlayerAdapter) PlaybackStatus() (PlaybackStatus, error) { return p.OnPlaybackStatus() } -func (p PlayerAdapter) Rate() (float64, error) { return p.OnRate() } -func (p PlayerAdapter) SetRate(rate float64) error { return p.OnSetRate(rate) } -func (p PlayerAdapter) Metadata() (Metadata, error) { return p.OnMetadata() } -func (p PlayerAdapter) Volume() (float64, error) { return p.OnVolume() } -func (p PlayerAdapter) SetVolume(vol float64) error { return p.OnSetVolume(vol) } -func (p PlayerAdapter) Position() (int64, error) { return p.OnPosition() } -func (p PlayerAdapter) MinimumRate() (float64, error) { return p.OnMinimumRate() } -func (p PlayerAdapter) MaximumRate() (float64, error) { return p.OnMaximumRate() } -func (p PlayerAdapter) CanGoNext() (bool, error) { return p.OnCanGoNext() } -func (p PlayerAdapter) CanGoPrevious() (bool, error) { return p.OnCanGoPrevious() } -func (p PlayerAdapter) CanPlay() (bool, error) { return p.OnCanPlay() } -func (p PlayerAdapter) CanPause() (bool, error) { return p.OnCanPause() } -func (p PlayerAdapter) CanSeek() (bool, error) { return p.OnCanSeek() } -func (p PlayerAdapter) CanControl() (bool, error) { return p.OnCanControl() } - -// NewPlayerAdapter creates a PlayerAdapter whose closures read from the accessor. -// name is the app name used in track object paths. -// accessor is a function that returns the current ModelAccessor, called on each read. -func NewPlayerAdapter(name string, accessor func() ModelAccessor, actions PlayerActions) PlayerAdapter { - return PlayerAdapter{ - OnNext: actions.Next, - OnPrevious: actions.Previous, - OnPause: actions.Pause, - OnPlayPause: actions.PlayPause, - OnStop: actions.Stop, - OnPlay: actions.Play, - OnSeek: actions.Seek, - OnSetPosition: actions.SetPosition, - OnOpenUri: func(string) error { return nil }, - OnPlaybackStatus: func() (PlaybackStatus, error) { - a := accessor() - if a.IsPlaying() { - return StatusPlaying, nil - } - if a.IsPaused() { - return StatusPaused, nil - } - return StatusStopped, nil - }, - OnRate: func() (float64, error) { return accessor().PlayerSpeed(), nil }, - OnSetRate: actions.SetRate, - OnMetadata: func() (Metadata, error) { - a := accessor() - title := a.CurrentTitle() - if title == "" { - return Metadata{ - TrackID: dbus.ObjectPath("/org/mpris/MediaPlayer2/NoTrack"), - }, nil - } - return Metadata{ - TrackID: trackPath(name, a.CurrentItemID()), - Length: time.Duration(a.PlayerDuration() * float64(time.Second)), - Title: title, - Artist: a.CurrentAuthors(), - }, nil - }, - OnVolume: func() (float64, error) { - return float64(accessor().PlayerVolume()) / 100.0, nil - }, - OnSetVolume: func(vol float64) error { - return actions.SetVolume(int(vol * 100)) - }, - OnPosition: func() (int64, error) { - return int64(accessor().PlayerPosition() * 1_000_000), nil - }, - OnMinimumRate: func() (float64, error) { return accessor().PlayerMinimumRate(), nil }, - OnMaximumRate: func() (float64, error) { return accessor().PlayerMaximumRate(), nil }, - OnCanGoNext: func() (bool, error) { return accessor().CanGoNext(), nil }, - OnCanGoPrevious: func() (bool, error) { return accessor().CanGoPrevious(), nil }, - OnCanPlay: func() (bool, error) { return true, nil }, - OnCanPause: func() (bool, error) { return true, nil }, - OnCanSeek: func() (bool, error) { return accessor().CanSeek(), nil }, - OnCanControl: func() (bool, error) { return true, nil }, - } -} - // trackPath returns the D-Bus object path that identifies an item as an MPRIS track. func trackPath(name, itemID string) dbus.ObjectPath { return dbus.ObjectPath(fmt.Sprintf("/org/%s/track/%s", name, strings.ReplaceAll(itemID, "-", "_"))) } -// PlayerActions defines the action callbacks for the PlayerAdapter. +// PlayerActions defines the callbacks of the methods and the writable +// properties of the org.mpris.MediaPlayer2.Player interface. type PlayerActions struct { Next func() error Previous func() error @@ -174,5 +87,6 @@ type PlayerActions struct { Seek func(offset time.Duration) error SetPosition func(trackId string, position time.Duration) error SetRate func(rate float64) error - SetVolume func(vol int) error + // SetVolume gets the MPRIS volume, where 1.0 is the app volume 100. + SetVolume func(volume float64) error } diff --git a/internal/mpris/bridge.go b/internal/mpris/bridge.go index 80bc6d2..3c05ae8 100644 --- a/internal/mpris/bridge.go +++ b/internal/mpris/bridge.go @@ -3,6 +3,7 @@ package mpris import ( "errors" "fmt" + "math" "sync" "time" @@ -16,7 +17,6 @@ type Bridge struct { program *tea.Program name string server *Server - player PlayerAdapter msgCh chan tea.Msg quitCh chan struct{} doneCh chan struct{} @@ -39,6 +39,17 @@ func NewBridge(program *tea.Program, name string) *Bridge { var errSkipSeek = errors.New("seek completed: returning error to bypass DE track-change debounce") +// maxVolume is the MPRIS volume of the app volume 150, the end of the scale +// of SetVolumeMsg. +const maxVolume = 1.5 + +// skipSeekAccessor reports Next and Previous as possible when an item is +// active and a seek is possible, because with a skip seek they seek. +type skipSeekAccessor struct{ ModelAccessor } + +func (a skipSeekAccessor) CanGoNext() bool { return a.HasActiveItem() && a.CanSeek() } +func (a skipSeekAccessor) CanGoPrevious() bool { return a.HasActiveItem() && a.CanSeek() } + // send dispatches a message to the bubbletea program via the buffered dispatcher without blocking the caller. func (b *Bridge) send(msg tea.Msg) { select { @@ -50,11 +61,15 @@ func (b *Bridge) send(msg tea.Msg) { } } -// Bind wires the adapter closures to read from accessor and send messages via program.Send(). +// Bind creates the MPRIS server. Its properties read from accessor, and its methods send messages via program.Send(). // accessor is a function that returns the current ModelAccessor, called on each read. // If skipSeekSeconds is more than 0, Next and Previous seek by that amount (non-standard MPRIS) // and do not change the track. func (b *Bridge) Bind(accessor func() ModelAccessor, skipSeekSeconds float64) { + if skipSeekSeconds > 0 { + appAccessor := accessor + accessor = func() ModelAccessor { return skipSeekAccessor{appAccessor()} } + } actions := PlayerActions{ Next: func() error { if skipSeekSeconds > 0 { @@ -97,27 +112,38 @@ func (b *Bridge) Bind(accessor func() ModelAccessor, skipSeekSeconds float64) { return nil }, SetPosition: func(trackId string, pos time.Duration) error { - // MPRIS: SetPosition has no effect if CanSeek is false, and a request - // for a track that is not the current track is stale. + // MPRIS: SetPosition has no effect if CanSeek is false or if the + // position is outside the track. A request for a track that is not + // the current track is stale. a := accessor() if !a.CanSeek() || trackId != string(trackPath(b.name, a.CurrentItemID())) { return nil } - b.send(SeekAbsoluteMsg{PositionSeconds: pos.Seconds()}) + seconds := pos.Seconds() + if seconds < 0 || (a.PlayerDuration() > 0 && seconds > a.PlayerDuration()) { + return nil + } + b.send(SeekAbsoluteMsg{PositionSeconds: seconds}) return nil }, SetRate: func(rate float64) error { - b.send(SetRateMsg{Rate: rate}) + // MPRIS: a rate of 0 acts as Pause. A rate is in the range of + // MinimumRate and MaximumRate. + if rate == 0 { + b.send(PauseMsg{}) + return nil + } + a := accessor() + b.send(SetRateMsg{Rate: min(max(rate, a.PlayerMinimumRate()), a.PlayerMaximumRate())}) return nil }, - SetVolume: func(vol int) error { - b.send(SetVolumeMsg{Volume: vol}) + SetVolume: func(volume float64) error { + // MPRIS: a negative volume is 0. + b.send(SetVolumeMsg{Volume: int(math.Round(min(max(volume, 0), maxVolume) * 100))}) return nil }, } - root := RootAdapter{Name: b.name} - b.player = NewPlayerAdapter(b.name, accessor, actions) - b.server = NewServer(b.name, root, b.player) + b.server = NewServer(b.name, RootAdapter{Name: b.name}, accessor, actions) } // Start runs the D-Bus server in a goroutine and starts the message dispatcher loop. @@ -141,10 +167,7 @@ func (b *Bridge) dispatchLoop() { select { case <-b.quitCh: return - case msg, ok := <-b.msgCh: - if !ok { - return - } + case msg := <-b.msgCh: if b.program != nil { b.program.Send(msg) } diff --git a/internal/mpris/bridge_test.go b/internal/mpris/bridge_test.go index eb50f32..27b8c53 100644 --- a/internal/mpris/bridge_test.go +++ b/internal/mpris/bridge_test.go @@ -2,8 +2,12 @@ package mpris import ( "fmt" + "math" "testing" "time" + + "github.com/godbus/dbus/v5" + "github.com/godbus/dbus/v5/prop" ) func TestBridgeMapsPlaybackActionsToExplicitMessages(t *testing.T) { @@ -15,10 +19,10 @@ func TestBridgeMapsPlaybackActionsToExplicitMessages(t *testing.T) { action func() error want string }{ - {name: "pause", action: bridge.player.Pause, want: "mpris.PauseMsg"}, - {name: "play", action: bridge.player.Play, want: "mpris.PlayMsg"}, - {name: "stop", action: bridge.player.Stop, want: "mpris.PauseMsg"}, - {name: "play pause", action: bridge.player.PlayPause, want: "mpris.PlayPauseMsg"}, + {name: "pause", action: bridge.server.actions.Pause, want: "mpris.PauseMsg"}, + {name: "play", action: bridge.server.actions.Play, want: "mpris.PlayMsg"}, + {name: "stop", action: bridge.server.actions.Stop, want: "mpris.PauseMsg"}, + {name: "play pause", action: bridge.server.actions.PlayPause, want: "mpris.PlayPauseMsg"}, } { t.Run(tt.name, func(t *testing.T) { if err := tt.action(); err != nil { @@ -35,13 +39,13 @@ func TestBridgeSkipsTrackOnNextAndPreviousByDefault(t *testing.T) { bridge := NewBridge(nil, "spruce") bridge.Bind(accessorFn(&mockAccessor{}), 0) - if err := bridge.player.Next(); err != nil { + if err := bridge.server.actions.Next(); err != nil { t.Fatalf("Next() error: %v", err) } if _, ok := (<-bridge.msgCh).(NextMsg); !ok { t.Fatal("Next() should send NextMsg") } - if err := bridge.player.Previous(); err != nil { + if err := bridge.server.actions.Previous(); err != nil { t.Fatalf("Previous() error: %v", err) } if _, ok := (<-bridge.msgCh).(PreviousMsg); !ok { @@ -54,13 +58,13 @@ func TestBridgeSeeksOnNextAndPreviousWithSkipSeekSeconds(t *testing.T) { bridge.Bind(accessorFn(&mockAccessor{}), 10) // The error return stops the desktop wait for a track change. - if err := bridge.player.Next(); err == nil { + if err := bridge.server.actions.Next(); err == nil { t.Fatal("Next() should return an error in seek mode") } if got := <-bridge.msgCh; got != (SeekRelativeMsg{OffsetSeconds: 10}) { t.Fatalf("Next() sent %#v; want SeekRelativeMsg{OffsetSeconds: 10}", got) } - if err := bridge.player.Previous(); err == nil { + if err := bridge.server.actions.Previous(); err == nil { t.Fatal("Previous() should return an error in seek mode") } if got := <-bridge.msgCh; got != (SeekRelativeMsg{OffsetSeconds: -10}) { @@ -72,11 +76,12 @@ func TestBridgeSetPositionAcceptsThePublishedTrackID(t *testing.T) { bridge := NewBridge(nil, "spruce") bridge.Bind(accessorFn(&mockAccessor{title: "Song", itemID: "t-1"}), 0) - meta, err := bridge.player.Metadata() - if err != nil { - t.Fatalf("Metadata() error: %v", err) + metadata, dbusErr := bridge.server.get(playerInterface, "Metadata") + if dbusErr != nil { + t.Fatalf("Get(Metadata) error: %v", dbusErr) } - if err := bridge.player.SetPosition(string(meta.TrackID), 30*time.Second); err != nil { + trackID := metadata.Value().(map[string]dbus.Variant)["mpris:trackid"].Value().(dbus.ObjectPath) + if err := bridge.server.actions.SetPosition(string(trackID), 30*time.Second); err != nil { t.Fatalf("SetPosition() error: %v", err) } @@ -90,23 +95,31 @@ func TestBridgeSetPositionAcceptsThePublishedTrackID(t *testing.T) { } } -func TestBridgeSetPositionIgnoresOtherTracks(t *testing.T) { +func TestBridgeSetPositionIgnoresStaleAndOutOfRangeRequests(t *testing.T) { for _, tt := range []struct { name string accessor *mockAccessor trackID string + // position is 30 seconds if it is 0. + position time.Duration }{ {name: "other track", accessor: &mockAccessor{title: "Song", itemID: "t-1"}, trackID: "/org/spruce/track/t_2"}, {name: "raw item id", accessor: &mockAccessor{title: "Song", itemID: "t-1"}, trackID: "t-1"}, {name: "empty id", accessor: &mockAccessor{title: "Song", itemID: "t-1"}, trackID: ""}, - {name: "no track", accessor: &mockAccessor{}, trackID: "/org/mpris/MediaPlayer2/NoTrack"}, + {name: "no track", accessor: &mockAccessor{}, trackID: "/org/mpris/MediaPlayer2/TrackList/NoTrack"}, {name: "seek not possible", accessor: &mockAccessor{title: "Mix", itemID: "mix", noSeek: true}, trackID: "/org/spruce/track/mix"}, + {name: "position before the start", accessor: &mockAccessor{title: "Song", itemID: "t-1"}, trackID: "/org/spruce/track/t_1", position: -time.Second}, + {name: "position past the end", accessor: &mockAccessor{title: "Song", itemID: "t-1", duration: 20}, trackID: "/org/spruce/track/t_1"}, } { t.Run(tt.name, func(t *testing.T) { bridge := NewBridge(nil, "spruce") bridge.Bind(accessorFn(tt.accessor), 0) - if err := bridge.player.SetPosition(tt.trackID, 30*time.Second); err != nil { + position := 30 * time.Second + if tt.position != 0 { + position = tt.position + } + if err := bridge.server.actions.SetPosition(tt.trackID, position); err != nil { t.Fatalf("SetPosition() error: %v", err) } @@ -118,3 +131,81 @@ func TestBridgeSetPositionIgnoresOtherTracks(t *testing.T) { }) } } + +func TestBridgeValidatesRateAndVolume(t *testing.T) { + bridge := NewBridge(nil, "spruce") + bridge.Bind(accessorFn(&mockAccessor{}), 0) + + for _, tt := range []struct { + name string + property string + value float64 + want any + }{ + // MPRIS: a rate of 0 acts as Pause. + {name: "rate zero", property: "Rate", value: 0, want: PauseMsg{}}, + {name: "rate below the minimum", property: "Rate", value: -1, want: SetRateMsg{Rate: 0.5}}, + {name: "rate above the maximum", property: "Rate", value: 100, want: SetRateMsg{Rate: 4}}, + {name: "rate in range", property: "Rate", value: 1.25, want: SetRateMsg{Rate: 1.25}}, + // MPRIS: a negative volume is 0. + {name: "negative volume", property: "Volume", value: -0.5, want: SetVolumeMsg{Volume: 0}}, + {name: "volume rounds", property: "Volume", value: 0.58, want: SetVolumeMsg{Volume: 58}}, + {name: "volume above the scale", property: "Volume", value: 2, want: SetVolumeMsg{Volume: 150}}, + } { + t.Run(tt.name, func(t *testing.T) { + if err := bridge.server.set(playerInterface, tt.property, dbus.MakeVariant(tt.value)); err != nil { + t.Fatalf("Set(%s, %v) error: %v", tt.property, tt.value, err) + } + select { + case got := <-bridge.msgCh: + if got != tt.want { + t.Errorf("Set(%s, %v) sent %#v; want %#v", tt.property, tt.value, got, tt.want) + } + default: + t.Errorf("Set(%s, %v) sent no message; want %#v", tt.property, tt.value, tt.want) + } + }) + } + + for _, property := range []string{"Rate", "Volume"} { + for _, value := range []float64{math.NaN(), math.Inf(1), math.Inf(-1)} { + if err := bridge.server.set(playerInterface, property, dbus.MakeVariant(value)); err != prop.ErrInvalidArg { + t.Errorf("Set(%s, %v) error = %v; want %v", property, value, err, prop.ErrInvalidArg) + } + select { + case got := <-bridge.msgCh: + t.Errorf("Set(%s, %v) sent %#v; want no message", property, value, got) + default: + } + } + } +} + +// TestBridgeSkipSeekReportsNextAndPreviousAsSeeks verifies that with a skip +// seek, CanGoNext and CanGoPrevious tell whether Next and Previous can seek. +func TestBridgeSkipSeekReportsNextAndPreviousAsSeeks(t *testing.T) { + for _, tt := range []struct { + name string + accessor *mockAccessor + want bool + }{ + {name: "empty queue", accessor: &mockAccessor{hasItem: true}, want: true}, + {name: "seek not possible", accessor: &mockAccessor{hasItem: true, queueLen: 2, noSeek: true}, want: false}, + {name: "no active item", accessor: &mockAccessor{}, want: false}, + } { + t.Run(tt.name, func(t *testing.T) { + bridge := NewBridge(nil, "pine") + bridge.Bind(accessorFn(tt.accessor), 10) + + for _, property := range []string{"CanGoNext", "CanGoPrevious"} { + value, err := bridge.server.get(playerInterface, property) + if err != nil { + t.Fatalf("Get(%s) error: %v", property, err) + } + if value.Value() != tt.want { + t.Errorf("%s = %v; want %v", property, value.Value(), tt.want) + } + } + }) + } +} diff --git a/internal/mpris/messages.go b/internal/mpris/messages.go index b285f89..e44e842 100644 --- a/internal/mpris/messages.go +++ b/internal/mpris/messages.go @@ -9,11 +9,6 @@ type PauseMsg struct{} // PlayMsg is sent when MPRIS requests playback to resume. type PlayMsg struct{} -// SeekMsg is sent when MPRIS requests a seek by offset (in seconds). -type SeekMsg struct { - Offset float64 -} - // SeekRelativeMsg is sent when MPRIS requests a relative seek by offset (in seconds). type SeekRelativeMsg struct { OffsetSeconds float64 diff --git a/internal/mpris/mpris_test.go b/internal/mpris/mpris_test.go index bdcb498..64f7fc8 100644 --- a/internal/mpris/mpris_test.go +++ b/internal/mpris/mpris_test.go @@ -1,8 +1,8 @@ package mpris import ( + "reflect" "testing" - "time" "github.com/godbus/dbus/v5" ) @@ -34,7 +34,6 @@ func (m *mockAccessor) PlayerVolume() int { return m.volume } func (m *mockAccessor) PlayerSpeed() float64 { return m.speed } func (m *mockAccessor) PlayerMinimumRate() float64 { return 0.5 } func (m *mockAccessor) PlayerMaximumRate() float64 { return 4.0 } -func (m *mockAccessor) QueueLength() int { return m.queueLen } func (m *mockAccessor) CanSeek() bool { return !m.noSeek } func (m *mockAccessor) CanGoNext() bool { return m.queueLen > 0 } func (m *mockAccessor) CanGoPrevious() bool { return true } @@ -43,6 +42,18 @@ func accessorFn(a *mockAccessor) func() ModelAccessor { return func() ModelAccessor { return a } } +// playerProperty returns the value of a player property of a server that +// reads the app state from a. +func playerProperty(t *testing.T, a *mockAccessor, name string) any { + t.Helper() + s := NewServer("spruce", RootAdapter{Name: "spruce"}, accessorFn(a), PlayerActions{}) + value, err := s.get(playerInterface, name) + if err != nil { + t.Fatalf("Get(%s) error: %v", name, err) + } + return value.Value() +} + func TestRootAdapterIdentity(t *testing.T) { r := RootAdapter{Name: "pine"} @@ -52,8 +63,9 @@ func TestRootAdapterIdentity(t *testing.T) { if v, err := r.DesktopEntry(); err != nil || v != "pine" { t.Errorf("DesktopEntry() = %q, %v; want %q, nil", v, err, "pine") } - if v, err := r.CanQuit(); err != nil || !v { - t.Errorf("CanQuit() = %v, %v; want true, nil", v, err) + // Quit does nothing, so MPRIS requires CanQuit to be false. + if v, err := r.CanQuit(); err != nil || v { + t.Errorf("CanQuit() = %v, %v; want false, nil", v, err) } if v, err := r.CanRaise(); err != nil || v { t.Errorf("CanRaise() = %v, %v; want false, nil", v, err) @@ -77,7 +89,7 @@ func TestRootAdapterIdentity(t *testing.T) { } } -func TestPlayerAdapterPlaybackStatus(t *testing.T) { +func TestServerPlaybackStatus(t *testing.T) { tests := []struct { name string accessor *mockAccessor @@ -89,19 +101,14 @@ func TestPlayerAdapterPlaybackStatus(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - p := NewPlayerAdapter("spruce", accessorFn(tt.accessor), PlayerActions{}) - got, err := p.PlaybackStatus() - if err != nil { - t.Fatalf("PlaybackStatus() error: %v", err) - } - if got != tt.want { - t.Errorf("PlaybackStatus() = %q; want %q", got, tt.want) + if got := playerProperty(t, tt.accessor, "PlaybackStatus"); got != string(tt.want) { + t.Errorf("PlaybackStatus = %q; want %q", got, tt.want) } }) } } -func TestPlayerAdapterVolumeConversion(t *testing.T) { +func TestServerVolumeConversion(t *testing.T) { tests := []struct { name string appVol int @@ -115,38 +122,14 @@ func TestPlayerAdapterVolumeConversion(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { a := &mockAccessor{volume: tt.appVol} - p := NewPlayerAdapter("spruce", accessorFn(a), PlayerActions{}) - got, err := p.Volume() - if err != nil { - t.Fatalf("Volume() error: %v", err) - } - if got != tt.wantMPRIS { - t.Errorf("Volume() = %v; want %v", got, tt.wantMPRIS) + if got := playerProperty(t, a, "Volume"); got != tt.wantMPRIS { + t.Errorf("Volume = %v; want %v", got, tt.wantMPRIS) } }) } } -func TestPlayerAdapterSetVolumeConversion(t *testing.T) { - var capturedVol int - actions := PlayerActions{ - SetVolume: func(vol int) error { - capturedVol = vol - return nil - }, - } - a := &mockAccessor{} - p := NewPlayerAdapter("spruce", accessorFn(a), actions) - - if err := p.SetVolume(0.75); err != nil { - t.Fatalf("SetVolume() error: %v", err) - } - if capturedVol != 75 { - t.Errorf("SetVolume(0.75) set app volume = %d; want 75", capturedVol) - } -} - -func TestPlayerAdapterMetadata(t *testing.T) { +func TestServerMetadata(t *testing.T) { a := &mockAccessor{ hasItem: true, title: "The Hobbit", @@ -154,126 +137,83 @@ func TestPlayerAdapterMetadata(t *testing.T) { itemID: "item-123", duration: 3600, } - p := NewPlayerAdapter("spruce", accessorFn(a), PlayerActions{}) - meta, err := p.Metadata() - if err != nil { - t.Fatalf("Metadata() error: %v", err) + metadata, ok := playerProperty(t, a, "Metadata").(map[string]dbus.Variant) + if !ok { + t.Fatalf("Metadata is not a{sv}") } - if meta.Title != "The Hobbit" { - t.Errorf("Metadata().Title = %q; want %q", meta.Title, "The Hobbit") + want := map[string]any{ + "mpris:trackid": dbus.ObjectPath("/org/spruce/track/item_123"), + "mpris:length": int64(3_600_000_000), + "xesam:title": "The Hobbit", + "xesam:artist": []string{"J.R.R. Tolkien"}, } - if len(meta.Artist) != 1 || meta.Artist[0] != "J.R.R. Tolkien" { - t.Errorf("Metadata().Artist = %v; want [J.R.R. Tolkien]", meta.Artist) + if len(metadata) != len(want) { + t.Errorf("Metadata has %d entries; want %d", len(metadata), len(want)) } - if meta.Length != time.Hour { - t.Errorf("Metadata().Length = %v; want %v", meta.Length, time.Hour) - } - expectedPath := dbus.ObjectPath("/org/spruce/track/item_123") - if meta.TrackID != expectedPath { - t.Errorf("Metadata().TrackID = %q; want %q", meta.TrackID, expectedPath) + for key, wantValue := range want { + if got := metadata[key].Value(); !reflect.DeepEqual(got, wantValue) { + t.Errorf("Metadata[%s] = %#v; want %#v", key, got, wantValue) + } } } -func TestPlayerAdapterMetadataNoItem(t *testing.T) { - a := &mockAccessor{} - p := NewPlayerAdapter("spruce", accessorFn(a), PlayerActions{}) - - meta, err := p.Metadata() - if err != nil { - t.Fatalf("Metadata() error: %v", err) +func TestServerMetadataNoItem(t *testing.T) { + metadata, ok := playerProperty(t, &mockAccessor{}, "Metadata").(map[string]dbus.Variant) + if !ok { + t.Fatalf("Metadata is not a{sv}") } - if meta.Title != "" { - t.Errorf("Metadata().Title = %q; want empty", meta.Title) + if _, ok := metadata["xesam:title"]; ok || len(metadata) != 1 { + t.Errorf("Metadata = %v; want only mpris:trackid", metadata) } -} - -func TestPlayerAdapterPosition(t *testing.T) { - a := &mockAccessor{position: 42.5} - p := NewPlayerAdapter("spruce", accessorFn(a), PlayerActions{}) - - pos, err := p.Position() - if err != nil { - t.Fatalf("Position() error: %v", err) - } - if pos != 42_500_000 { - t.Errorf("Position() = %d; want 42500000", pos) + // MPRIS reserves this path for no track. + if got, want := metadata["mpris:trackid"].Value(), dbus.ObjectPath("/org/mpris/MediaPlayer2/TrackList/NoTrack"); got != want { + t.Errorf("Metadata[mpris:trackid] = %#v; want %#v", got, want) } } -func TestPlayerAdapterSeek(t *testing.T) { - var capturedOffset time.Duration - actions := PlayerActions{ - Seek: func(offset time.Duration) error { - capturedOffset = offset - return nil - }, +// TestServerCanPlayAndPauseNeedAnItem verifies that Play and Pause are +// possible only with a current item. Without one, Play does nothing. +func TestServerCanPlayAndPauseNeedAnItem(t *testing.T) { + for _, hasItem := range []bool{false, true} { + a := &mockAccessor{hasItem: hasItem} + for _, property := range []string{"CanPlay", "CanPause"} { + if got := playerProperty(t, a, property); got != hasItem { + t.Errorf("%s with an item %v = %v; want %v", property, hasItem, got, hasItem) + } + } } - a := &mockAccessor{} - p := NewPlayerAdapter("spruce", accessorFn(a), actions) +} - if err := p.Seek(10 * time.Second); err != nil { - t.Fatalf("Seek() error: %v", err) - } - if capturedOffset != 10*time.Second { - t.Errorf("Seek(10s) captured = %v; want 10s", capturedOffset) +func TestServerPosition(t *testing.T) { + if got := playerProperty(t, &mockAccessor{position: 42.5}, "Position"); got != int64(42_500_000) { + t.Errorf("Position = %#v; want int64(42500000)", got) } } -func TestPlayerAdapterCanGoNext(t *testing.T) { +func TestServerCanGoNext(t *testing.T) { a := &mockAccessor{queueLen: 2} - p := NewPlayerAdapter("spruce", accessorFn(a), PlayerActions{}) - - v, err := p.CanGoNext() - if err != nil { - t.Fatalf("CanGoNext() error: %v", err) - } - if !v { - t.Error("CanGoNext() = false; want true (queue has items)") + if got := playerProperty(t, a, "CanGoNext"); got != true { + t.Error("CanGoNext = false; want true (queue has items)") } a.queueLen = 0 - v, err = p.CanGoNext() - if err != nil { - t.Fatalf("CanGoNext() error: %v", err) - } - if v { - t.Error("CanGoNext() = true; want false (empty queue)") + if got := playerProperty(t, a, "CanGoNext"); got != false { + t.Error("CanGoNext = true; want false (empty queue)") } } -func TestPlayerAdapterCanControl(t *testing.T) { - a := &mockAccessor{} - p := NewPlayerAdapter("spruce", accessorFn(a), PlayerActions{}) - - v, err := p.CanControl() - if err != nil { - t.Fatalf("CanControl() error: %v", err) - } - if !v { - t.Error("CanControl() = false; want true") +func TestServerCanControl(t *testing.T) { + if got := playerProperty(t, &mockAccessor{}, "CanControl"); got != true { + t.Error("CanControl = false; want true") } } -func TestPlayerAdapterRates(t *testing.T) { +func TestServerRates(t *testing.T) { a := &mockAccessor{speed: 1.5} - p := NewPlayerAdapter("spruce", accessorFn(a), PlayerActions{}) - - rate, err := p.Rate() - if err != nil { - t.Fatalf("Rate() error: %v", err) - } - if rate != 1.5 { - t.Errorf("Rate() = %v; want 1.5", rate) - } - - min, err := p.MinimumRate() - if err != nil || min != 0.5 { - t.Errorf("MinimumRate() = %v, %v; want 0.5, nil", min, err) - } - - max, err := p.MaximumRate() - if err != nil || max != 4.0 { - t.Errorf("MaximumRate() = %v, %v; want 4.0, nil", max, err) + for name, want := range map[string]float64{"Rate": 1.5, "MinimumRate": 0.5, "MaximumRate": 4.0} { + if got := playerProperty(t, a, name); got != want { + t.Errorf("%s = %v; want %v", name, got, want) + } } } diff --git a/internal/mpris/server.go b/internal/mpris/server.go index 08d7413..e216e47 100644 --- a/internal/mpris/server.go +++ b/internal/mpris/server.go @@ -2,6 +2,7 @@ package mpris import ( "fmt" + "math" "sync" "time" @@ -40,12 +41,18 @@ func readWrite(name string, get func() (float64, error), set func(float64) error return p } +// fromState returns a property getter that reads value from the app state on +// each request. +func fromState[T any](accessor func() ModelAccessor, value func(ModelAccessor) T) func() (T, error) { + return func() (T, error) { return value(accessor()), nil } +} + // Server is an MPRIS media player on the D-Bus session bus. It has the // org.mpris.MediaPlayer2 and org.mpris.MediaPlayer2.Player interfaces. type Server struct { name string root RootAdapter - player PlayerAdapter + actions PlayerActions properties map[string][]property mu sync.Mutex @@ -53,20 +60,18 @@ type Server struct { stopped bool } -// NewServer creates an MPRIS server for the app name with the given root and player adapters. -func NewServer(name string, root RootAdapter, player PlayerAdapter) *Server { - status := func() (string, error) { - status, err := player.PlaybackStatus() - return string(status), err - } - metadata := func() (map[string]dbus.Variant, error) { - metadata, err := player.Metadata() - return metadata.variants(), err - } +// NewServer creates an MPRIS server for the app name. The player properties +// read the app state from accessor on each request, and the player methods +// and the writable properties call actions. +func NewServer(name string, root RootAdapter, accessor func() ModelAccessor, actions PlayerActions) *Server { + status := func(a ModelAccessor) string { return string(playbackStatus(a)) } + metadata := func(a ModelAccessor) map[string]dbus.Variant { return trackMetadata(name, a).variants() } + volume := func(a ModelAccessor) float64 { return float64(a.PlayerVolume()) / 100.0 } + position := func(a ModelAccessor) int64 { return int64(a.PlayerPosition() * 1_000_000) } return &Server{ - name: name, - root: root, - player: player, + name: name, + root: root, + actions: actions, properties: map[string][]property{ rootInterface: { readOnly("CanQuit", "b", root.CanQuit), @@ -78,19 +83,19 @@ func NewServer(name string, root RootAdapter, player PlayerAdapter) *Server { readOnly("SupportedMimeTypes", "as", root.SupportedMimeTypes), }, playerInterface: { - readOnly("PlaybackStatus", "s", status), - readWrite("Rate", player.Rate, player.SetRate), - readOnly("Metadata", "a{sv}", metadata), - readWrite("Volume", player.Volume, player.SetVolume), - readOnly("Position", "x", player.Position), - readOnly("MinimumRate", "d", player.MinimumRate), - readOnly("MaximumRate", "d", player.MaximumRate), - readOnly("CanGoNext", "b", player.CanGoNext), - readOnly("CanGoPrevious", "b", player.CanGoPrevious), - readOnly("CanPlay", "b", player.CanPlay), - readOnly("CanPause", "b", player.CanPause), - readOnly("CanSeek", "b", player.CanSeek), - readOnly("CanControl", "b", player.CanControl), + readOnly("PlaybackStatus", "s", fromState(accessor, status)), + readWrite("Rate", fromState(accessor, ModelAccessor.PlayerSpeed), actions.SetRate), + readOnly("Metadata", "a{sv}", fromState(accessor, metadata)), + readWrite("Volume", fromState(accessor, volume), actions.SetVolume), + readOnly("Position", "x", fromState(accessor, position)), + readOnly("MinimumRate", "d", fromState(accessor, ModelAccessor.PlayerMinimumRate)), + readOnly("MaximumRate", "d", fromState(accessor, ModelAccessor.PlayerMaximumRate)), + readOnly("CanGoNext", "b", fromState(accessor, ModelAccessor.CanGoNext)), + readOnly("CanGoPrevious", "b", fromState(accessor, ModelAccessor.CanGoPrevious)), + readOnly("CanPlay", "b", fromState(accessor, ModelAccessor.HasActiveItem)), + readOnly("CanPause", "b", fromState(accessor, ModelAccessor.HasActiveItem)), + readOnly("CanSeek", "b", fromState(accessor, ModelAccessor.CanSeek)), + readOnly("CanControl", "b", func() (bool, error) { return true, nil }), }, }, } @@ -149,7 +154,7 @@ func (s *Server) Stop() error { // export puts the MPRIS object on the connection and then takes the bus name. func (s *Server) export(conn *dbus.Conn) error { - player := s.player + player := s.actions call := func(method func() error) func() *dbus.Error { return func() *dbus.Error { return failed(method()) } } @@ -171,7 +176,7 @@ func (s *Server) export(conn *dbus.Conn) error { "SetPosition": func(trackID dbus.ObjectPath, position int64) *dbus.Error { return failed(player.SetPosition(string(trackID), microseconds(position))) }, - "OpenUri": func(uri string) *dbus.Error { return failed(player.OpenUri(uri)) }, + "OpenUri": func(string) *dbus.Error { return nil }, }, propertiesInterface: { "Get": s.get, @@ -259,7 +264,8 @@ func (s *Server) set(iface, name string, value dbus.Variant) *dbus.Error { return prop.ErrReadOnly } number, ok := value.Value().(float64) - if !ok { + // The writable properties are the rate and the volume. Each is finite. + if !ok || math.IsNaN(number) || math.IsInf(number, 0) { return prop.ErrInvalidArg } return failed(p.set(number)) @@ -338,11 +344,14 @@ func (s *Server) changed(names ...string) { // PlaybackChanged tells MPRIS clients that the playback state, the rate, or // the track changed. func (s *Server) PlaybackChanged() { - s.changed("PlaybackStatus", "Rate", "Metadata", "MinimumRate", "MaximumRate") + s.changed("PlaybackStatus", "CanPlay", "CanPause", "CanGoNext", "CanGoPrevious", "Rate", "Metadata", "MinimumRate", "MaximumRate") } -// StatusChanged tells MPRIS clients that the playback status changed. -func (s *Server) StatusChanged() { s.changed("PlaybackStatus") } +// StatusChanged tells MPRIS clients that the playback status changed, and with +// it CanPlay, CanPause, CanGoNext, and CanGoPrevious. +func (s *Server) StatusChanged() { + s.changed("PlaybackStatus", "CanPlay", "CanPause", "CanGoNext", "CanGoPrevious") +} // MetadataChanged tells MPRIS clients that the track metadata changed. func (s *Server) MetadataChanged() { s.changed("Metadata") } @@ -350,7 +359,9 @@ func (s *Server) MetadataChanged() { s.changed("Metadata") } // VolumeChanged tells MPRIS clients that the volume changed. func (s *Server) VolumeChanged() { s.changed("Volume") } -// Seeked tells MPRIS clients the playback position, in seconds. +// Seeked tells MPRIS clients that the position changed in a way that the rate +// does not explain, for example by a seek. positionSeconds is the new +// position. During playback, a client computes the position from the rate. func (s *Server) Seeked(positionSeconds float64) { conn := s.connection() if conn == nil { diff --git a/internal/mpris/server_linux_test.go b/internal/mpris/server_linux_test.go index cdfbc10..55fc69f 100644 --- a/internal/mpris/server_linux_test.go +++ b/internal/mpris/server_linux_test.go @@ -5,6 +5,7 @@ package mpris import ( "bufio" "context" + "math" "os" "os/exec" "reflect" @@ -156,7 +157,7 @@ func TestServerOnSessionBus(t *testing.T) { "xesam:artist": []string{"J.R.R. Tolkien"}, } wantRoot := map[string]any{ - "CanQuit": true, + "CanQuit": false, "CanRaise": false, "HasTrackList": false, "Identity": "pinetest", @@ -325,16 +326,31 @@ func TestServerOnSessionBus(t *testing.T) { t.Errorf("Set(Rate) error: %v", err) } wantMessage(t, "Set(Rate)", SetRateMsg{Rate: 2}) - - // A value of a wrong type must give an error. It must not reach the app. - err := busCall(t, obj, testPropsIface+".Set", testPlayerIface, "Volume", dbus.MakeVariant("loud")).Err - if got, want := errorName(err), "org.freedesktop.DBus.Properties.Error.InvalidArg"; got != want { - t.Errorf("Set(Volume) with a string: error = %q (%v); want %q", got, err, want) + // MPRIS: a rate of 0 acts as Pause. + if err := busCall(t, obj, testPropsIface+".Set", testPlayerIface, "Rate", dbus.MakeVariant(0.0)).Err; err != nil { + t.Errorf("Set(Rate, 0) error: %v", err) } - select { - case got := <-bridge.msgCh: - t.Errorf("Set(Volume) with a string sent %#v; want no message", got) - default: + wantMessage(t, "Set(Rate, 0)", PauseMsg{}) + + // A value of a wrong type or a value that is not a number must give + // an error. It must not reach the app. + for _, tt := range []struct { + property string + value any + }{ + {property: "Volume", value: "loud"}, + {property: "Volume", value: math.NaN()}, + {property: "Rate", value: math.NaN()}, + } { + err := busCall(t, obj, testPropsIface+".Set", testPlayerIface, tt.property, dbus.MakeVariant(tt.value)).Err + if got, want := errorName(err), "org.freedesktop.DBus.Properties.Error.InvalidArg"; got != want { + t.Errorf("Set(%s, %v): error = %q (%v); want %q", tt.property, tt.value, got, err, want) + } + select { + case got := <-bridge.msgCh: + t.Errorf("Set(%s, %v) sent %#v; want no message", tt.property, tt.value, got) + default: + } } }) @@ -376,7 +392,7 @@ func TestServerOnSessionBus(t *testing.T) { server.PlaybackChanged() changed := waitChanged(t) - checkValues(t, changed, map[string]any{"PlaybackStatus": "Playing", "Rate": 1.5, "MinimumRate": 0.5, "MaximumRate": 4.0}) + checkValues(t, changed, map[string]any{"PlaybackStatus": "Playing", "CanPlay": true, "CanPause": true, "CanGoNext": true, "CanGoPrevious": true, "Rate": 1.5, "MinimumRate": 0.5, "MaximumRate": 4.0}) metadata, ok := changed["Metadata"].Value().(map[string]dbus.Variant) if !ok { t.Fatalf("PlaybackChanged sent Metadata with signature %s; want a{sv}", changed["Metadata"].Signature()) @@ -388,7 +404,7 @@ func TestServerOnSessionBus(t *testing.T) { emit func() want map[string]any }{ - {name: "StatusChanged", emit: server.StatusChanged, want: map[string]any{"PlaybackStatus": "Playing"}}, + {name: "StatusChanged", emit: server.StatusChanged, want: map[string]any{"PlaybackStatus": "Playing", "CanPlay": true, "CanPause": true, "CanGoNext": true, "CanGoPrevious": true}}, {name: "VolumeChanged", emit: server.VolumeChanged, want: map[string]any{"Volume": 0.75}}, } { tt.emit() diff --git a/internal/player/cache.go b/internal/player/cache.go index c401d2d..17f0ccd 100644 --- a/internal/player/cache.go +++ b/internal/player/cache.go @@ -36,7 +36,7 @@ type SessionCache struct { // NewSessionCache creates a private cache directory that mpv can access. func NewSessionCache(maxBytes int64) (*SessionCache, error) { - root, err := MpvSocketDir() + root, err := runtimeDir() if err != nil { return nil, fmt.Errorf("resolve media cache directory: %w", err) } @@ -91,6 +91,7 @@ func (c *SessionCache) Store(ctx context.Context, itemID string, download MediaD return path, nil } + // Close also takes downloadMu, so the cache cannot close while Store runs. c.downloadMu.Lock() defer c.downloadMu.Unlock() @@ -156,11 +157,6 @@ func (c *SessionCache) Store(ctx context.Context, itemID string, download MediaD complete = true c.mu.Lock() - if c.closed { - c.mu.Unlock() - _ = os.Remove(path) - return "", errors.New("media cache is closed") - } c.paths[itemID] = path c.usedBytes += limited.written c.mu.Unlock() diff --git a/internal/player/commands.go b/internal/player/commands.go index 6f8449b..48fe5f2 100644 --- a/internal/player/commands.go +++ b/internal/player/commands.go @@ -2,6 +2,7 @@ package player import ( "fmt" + "strconv" "time" "github.com/Thelost77/pine/internal/logger" @@ -117,32 +118,14 @@ type PlayerLaunchErrMsg struct { // PlayerQuitMsg signals that mpv has been quit. type PlayerQuitMsg struct{} -// formatStartPosition builds mpv's --start value. -// If duration is known and start is past 0, it uses a percent so mpv can jump -// by byte offset instead of scanning to a timestamp. -func formatStartPosition(startTime, duration float64) string { - if duration > 0 && startTime > 0 { - pct := startTime / duration * 100 - if pct > 100 { - pct = 100 - } - return fmt.Sprintf("%f%%", pct) - } - return fmt.Sprintf("%f", startTime) -} - -// LaunchCmd starts playback. If paused is true, mpv starts paused. -// httpHeaders are the HTTP request headers of the stream. -// duration is the current track length in seconds; it is used to start at a -// percent offset when resuming into a long HTTP stream. Pass 0 to start at -// startTime in seconds. +// LaunchCmd starts playback at startTime in seconds. If paused is true, mpv +// starts paused. httpHeaders are the HTTP request headers of the stream. // Returns PlayerReadyMsg when mpv has accepted the file. A file that fails to // load ends the playback later. -func LaunchCmd(p Player, url string, startTime, duration float64, paused bool, httpHeaders []string, volume int, generation uint64) tea.Cmd { +func LaunchCmd(p Player, url string, startTime float64, paused bool, httpHeaders []string, volume int, generation uint64) tea.Cmd { return func() tea.Msg { - startStr := formatStartPosition(startTime, duration) - logger.Info("launching mpv", "startTime", startTime, "duration", duration, "start", startStr, "generation", generation) - if err := p.Launch(url, startStr, paused, httpHeaders, volume); err != nil { + logger.Info("launching mpv", "startTime", startTime, "generation", generation) + if err := p.Launch(url, strconv.FormatFloat(startTime, 'f', -1, 64), paused, httpHeaders, volume); err != nil { logger.Error("mpv launch failed", "err", err) return PlayerLaunchErrMsg{Generation: generation, Err: err} } @@ -158,24 +141,12 @@ func QuitCmd(p Player) tea.Cmd { } } -// SeekCmd sends an absolute seek request to mpv by target seconds. +// SeekCmd sends an absolute seek request to mpv by target seconds. It returns +// no message: Seek logs a failure, and the next position tick has the +// position of the player. func SeekCmd(p Player, target float64) tea.Cmd { return func() tea.Msg { - err := p.Seek(target) - if err != nil { - return PositionMsg{Err: err} - } - return nil - } -} - -// SeekRelativeCmd sends a relative seek request to mpv by offset seconds. -func SeekRelativeCmd(p Player, offset float64) tea.Cmd { - return func() tea.Msg { - err := p.SeekRelative(offset) - if err != nil { - return PositionMsg{Err: err} - } + _ = p.Seek(target) return nil } } diff --git a/internal/player/commands_test.go b/internal/player/commands_test.go index 6a6a5aa..fa79846 100644 --- a/internal/player/commands_test.go +++ b/internal/player/commands_test.go @@ -1,7 +1,6 @@ package player import ( - "fmt" "testing" tea "github.com/charmbracelet/bubbletea" @@ -12,7 +11,7 @@ import ( // root model can discard stale launch errors from superseded sessions. func TestLaunchCmdPropagatesGenerationToLaunchError(t *testing.T) { mp := &launchFailPlayer{} - cmd := LaunchCmd(mp, "http://test/audio.mp3", 0, 0, false, nil, 100, 7) + cmd := LaunchCmd(mp, "http://test/audio.mp3", 0, false, nil, 100, 7) msg := cmd() launchErr, ok := msg.(PlayerLaunchErrMsg) if !ok { @@ -34,48 +33,6 @@ func TestPlayerReadyMsgAndLaunchErrMsgZeroValueGeneration(t *testing.T) { } } -func TestFormatStartPosition(t *testing.T) { - tests := []struct { - name string - startTime float64 - duration float64 - want string - }{ - { - name: "late resume uses percent", - startTime: 93767, - duration: 124076, - want: fmt.Sprintf("%f%%", 93767.0/124076.0*100), - }, - { - name: "unknown duration uses seconds", - startTime: 30, - duration: 0, - want: fmt.Sprintf("%f", 30.0), - }, - { - name: "start at zero uses seconds", - startTime: 0, - duration: 124076, - want: fmt.Sprintf("%f", 0.0), - }, - { - name: "past end clamps to 100 percent", - startTime: 200, - duration: 100, - want: fmt.Sprintf("%f%%", 100.0), - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := formatStartPosition(tt.startTime, tt.duration) - if got != tt.want { - t.Fatalf("formatStartPosition(%v, %v) = %q, want %q", tt.startTime, tt.duration, got, tt.want) - } - }) - } -} - // launchFailPlayer implements Player and fails Launch, so that LaunchCmd // returns PlayerLaunchErrMsg. type launchFailPlayer struct{} @@ -83,17 +40,15 @@ type launchFailPlayer struct{} func (launchFailPlayer) Launch(url, startTime string, paused bool, httpHeaders []string, volume int) error { return errLaunchSentinel } -func (launchFailPlayer) GetPosition() (float64, error) { return 0, nil } -func (launchFailPlayer) GetDuration() (float64, error) { return 0, nil } -func (launchFailPlayer) GetPaused() (bool, error) { return false, nil } -func (launchFailPlayer) GetIdle() (bool, error) { return false, nil } -func (launchFailPlayer) SetPause(paused bool) error { return nil } -func (launchFailPlayer) Seek(seconds float64) error { return nil } -func (launchFailPlayer) SeekRelative(seconds float64) error { return nil } -func (launchFailPlayer) SetSpeed(speed float64) error { return nil } -func (launchFailPlayer) SetVolume(vol int) error { return nil } -func (launchFailPlayer) GetVolume() (int, error) { return 100, nil } -func (launchFailPlayer) Quit() error { return nil } +func (launchFailPlayer) GetPosition() (float64, error) { return 0, nil } +func (launchFailPlayer) GetDuration() (float64, error) { return 0, nil } +func (launchFailPlayer) GetPaused() (bool, error) { return false, nil } +func (launchFailPlayer) GetIdle() (bool, error) { return false, nil } +func (launchFailPlayer) SetPause(paused bool) error { return nil } +func (launchFailPlayer) Seek(seconds float64) error { return nil } +func (launchFailPlayer) SetSpeed(speed float64) error { return nil } +func (launchFailPlayer) SetVolume(vol int) error { return nil } +func (launchFailPlayer) Quit() error { return nil } var errLaunchSentinel = &sentinelError{"launch failed"} diff --git a/internal/player/group_test.go b/internal/player/group_test.go index 060c78f..21db327 100644 --- a/internal/player/group_test.go +++ b/internal/player/group_test.go @@ -151,8 +151,8 @@ func TestGroupLoopsTracksThroughLibmpv(t *testing.T) { if paused, err := m.GetPaused(); err != nil || paused { t.Errorf("member %d GetPaused() = %v, %v, want false", i, paused, err) } - if volume, err := m.GetVolume(); err != nil || volume != 20 { - t.Errorf("member %d GetVolume() = %d, %v, want 20", i, volume, err) + if volume, err := m.handle.getDouble("volume"); err != nil || volume != 20 { + t.Errorf("member %d volume = %v, %v, want 20", i, volume, err) } } diff --git a/internal/player/libmpv.go b/internal/player/libmpv.go index cd8bb6e..35d7ba8 100644 --- a/internal/player/libmpv.go +++ b/internal/player/libmpv.go @@ -50,13 +50,20 @@ type mpvLogMessage struct { text *byte } -// urlQuery matches the query of a URL in an mpv message. -var urlQuery = regexp.MustCompile(`\?[^\s"']+`) +var ( + // urlUserinfo matches the user and the password of a URL in an mpv + // message. + urlUserinfo = regexp.MustCompile(`://[^/?#@\s"']+@`) + // urlQuery matches the query of a URL in an mpv message. + urlQuery = regexp.MustCompile(`\?[^\s"']+`) +) // logText returns the text of the message for the app log. It removes the -// query of each URL, because a query can hold a token. +// user, the password, and the query of each URL, because they can hold a +// secret. func (m *mpvLogMessage) logText() string { - return urlQuery.ReplaceAllString(strings.TrimSpace(cString(m.text)), "?") + text := urlUserinfo.ReplaceAllString(strings.TrimSpace(cString(m.text)), "://@") + return urlQuery.ReplaceAllString(text, "?") } // cString copies a NUL-terminated C string. diff --git a/internal/player/libmpv_test.go b/internal/player/libmpv_test.go index 91715d2..0f496e2 100644 --- a/internal/player/libmpv_test.go +++ b/internal/player/libmpv_test.go @@ -240,7 +240,8 @@ func TestLibmpvHandleLogMessagesGiveTheCauseWithoutSecrets(t *testing.T) { })) t.Cleanup(srv.Close) - texts := collectLogMessages(t, mpvLogLevel, srv.URL+"/book.wav?token=query-secret") + streamURL := strings.Replace(srv.URL, "://", "://reader:userinfo-secret@", 1) + "/book.wav?token=query-secret" + texts := collectLogMessages(t, mpvLogLevel, streamURL) all := strings.Join(texts, "\n") if !strings.Contains(all, "404") { @@ -249,7 +250,7 @@ func TestLibmpvHandleLogMessagesGiveTheCauseWithoutSecrets(t *testing.T) { if !strings.Contains(all, "/book.wav") { t.Errorf("the log messages do not name the stream: %q", texts) } - for _, secret := range []string{testAuthValue, "query-secret"} { + for _, secret := range []string{testAuthValue, "userinfo-secret", "query-secret"} { if strings.Contains(all, secret) { t.Errorf("the log messages contain the secret %q: %q", secret, texts) } diff --git a/internal/player/model.go b/internal/player/model.go index ce04c7e..1347e9f 100644 --- a/internal/player/model.go +++ b/internal/player/model.go @@ -119,17 +119,6 @@ func (m Model) VolumeUpKey() key.Binding { return m.keys.VolumeUp } // VolumeDownKey returns the volume-down key binding. func (m Model) VolumeDownKey() key.Binding { return m.keys.VolumeDown } -// HandlesKey reports whether the player should consume the key while a session is active. -func (m Model) HandlesKey(msg tea.KeyMsg) bool { - return key.Matches(msg, m.keys.PlayPause) || - key.Matches(msg, m.keys.SeekForward) || - key.Matches(msg, m.keys.SeekBack) || - key.Matches(msg, m.keys.SpeedUp) || - key.Matches(msg, m.keys.SpeedDown) || - key.Matches(msg, m.keys.VolumeUp) || - key.Matches(msg, m.keys.VolumeDown) -} - // Update handles messages for the player sub-model. func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { switch msg := msg.(type) { diff --git a/internal/player/mpv.go b/internal/player/mpv.go index 2785501..fdf0159 100644 --- a/internal/player/mpv.go +++ b/internal/player/mpv.go @@ -31,10 +31,10 @@ func SetAppName(name string) { mpvSocketDir = "" } -// MpvSocketDir returns the private runtime directory of the app: +// runtimeDir returns the private runtime directory of the app: // /tmp/-runtime- with 0700 permissions. The media cache is in // this directory. -func MpvSocketDir() (string, error) { +func runtimeDir() (string, error) { mpvSocketDirMu.Lock() defer mpvSocketDirMu.Unlock() if mpvSocketDir != "" { @@ -80,10 +80,8 @@ type Player interface { GetIdle() (bool, error) SetPause(paused bool) error Seek(seconds float64) error - SeekRelative(seconds float64) error SetSpeed(speed float64) error SetVolume(vol int) error - GetVolume() (int, error) Quit() error } @@ -97,8 +95,8 @@ type Mpv struct { handle mpvHandle play *playback - // ForceSeekable sets force-seekable=yes at launch, so that mpv can start - // a long HTTP stream at a percent offset. + // ForceSeekable sets force-seekable=yes at launch, so that mpv can seek + // in an HTTP stream that it does not find seekable. ForceSeekable bool // audioOutput sets the mpv option ao. The tests use "null". @@ -361,17 +359,6 @@ func (m *Mpv) Seek(seconds float64) error { return err } -// SeekRelative seeks by a relative offset in seconds. -func (m *Mpv) SeekRelative(seconds float64) error { - err := m.withHandle("seek relative", func(h mpvHandle) error { - return h.command("seek", strconv.FormatFloat(seconds, 'f', -1, 64), "relative") - }) - if err != nil { - logger.Warn("failed to seek relative mpv", "seconds", seconds, "err", err) - } - return err -} - // SetSpeed sets the playback speed multiplier. func (m *Mpv) SetSpeed(speed float64) error { err := m.withHandle("set speed", func(h mpvHandle) error { @@ -394,15 +381,6 @@ func (m *Mpv) SetVolume(vol int) error { return err } -// GetVolume returns the current volume level. -func (m *Mpv) GetVolume() (int, error) { - v, err := m.getFloat("volume") - if err != nil { - return 0, err - } - return int(v), nil -} - // Quit stops playback and destroys the mpv handle. func (m *Mpv) Quit() error { m.opMu.Lock() diff --git a/internal/player/mpv_test.go b/internal/player/mpv_test.go index c417f51..13113fd 100644 --- a/internal/player/mpv_test.go +++ b/internal/player/mpv_test.go @@ -76,7 +76,7 @@ func resetMpvSocketDirForTest(t *testing.T) { }) } -func TestMpvSocketDirRetriesAfterPreparationFailure(t *testing.T) { +func TestRuntimeDirRetriesAfterPreparationFailure(t *testing.T) { resetMpvSocketDirForTest(t) root := t.TempDir() setTempDir(t, root) @@ -90,7 +90,7 @@ func TestMpvSocketDirRetriesAfterPreparationFailure(t *testing.T) { } } - if _, err := MpvSocketDir(); err == nil { + if _, err := runtimeDir(); err == nil { t.Fatal("expected socket directory preparation error") } for _, path := range paths { @@ -99,9 +99,9 @@ func TestMpvSocketDirRetriesAfterPreparationFailure(t *testing.T) { } } - dir, err := MpvSocketDir() + dir, err := runtimeDir() if err != nil { - t.Fatalf("MpvSocketDir() retry error: %v", err) + t.Fatalf("runtimeDir() retry error: %v", err) } if dir != paths[0] { t.Fatalf("socket directory = %q, want primary %q", dir, paths[0]) @@ -143,7 +143,7 @@ func TestDescribeStreamURLInvalid(t *testing.T) { } } -func TestSetAppNameNamesTheSocketDirectory(t *testing.T) { +func TestSetAppNameNamesTheRuntimeDirectory(t *testing.T) { resetMpvSocketDirForTest(t) previous := appName t.Cleanup(func() { SetAppName(previous) }) @@ -152,13 +152,13 @@ func TestSetAppNameNamesTheSocketDirectory(t *testing.T) { SetAppName("pine") - dir, err := MpvSocketDir() + dir, err := runtimeDir() if err != nil { - t.Fatalf("MpvSocketDir() error: %v", err) + t.Fatalf("runtimeDir() error: %v", err) } want := filepath.Join(root, fmt.Sprintf("pine-runtime-%d", os.Getuid())) if dir != want { - t.Fatalf("MpvSocketDir() = %q, want %q", dir, want) + t.Fatalf("runtimeDir() = %q, want %q", dir, want) } } @@ -254,8 +254,7 @@ func TestMpvLaunchAppliesHeaderStartPauseAndVolume(t *testing.T) { m := newTestMpv(t) m.ForceSeekable = true - start := formatStartPosition(60, 120) - if err := m.Launch(srv.URL+"/long.wav", start, true, []string{testAuthHeader}, 35); err != nil { + if err := m.Launch(srv.URL+"/long.wav", "60", true, []string{testAuthHeader}, 35); err != nil { t.Fatalf("Launch() error: %v", err) } @@ -271,14 +270,32 @@ func TestMpvLaunchAppliesHeaderStartPauseAndVolume(t *testing.T) { if paused, err := m.GetPaused(); err != nil || !paused { t.Errorf("GetPaused() = %v, %v, want true", paused, err) } - if volume, err := m.GetVolume(); err != nil || volume != 35 { - t.Errorf("GetVolume() = %d, %v, want 35", volume, err) + if volume, err := m.handle.getDouble("volume"); err != nil || volume != 35 { + t.Errorf("volume = %v, %v, want 35", volume, err) } if forced, err := m.handle.getFlag("force-seekable"); err != nil || !forced { t.Errorf("force-seekable = %v, %v, want true with ForceSeekable", forced, err) } } +// TestLaunchCmdStartsAtTheStartTime verifies that playback starts at the start +// time in seconds. A percent start does not: mpv multiplies it by the length +// that mpv finds, and the server can report another length. +func TestLaunchCmdStartsAtTheStartTime(t *testing.T) { + srv := newAudioServer(t) + m := newTestMpv(t) + m.ForceSeekable = true + + msg := LaunchCmd(m, srv.URL+"/long.wav", 60, true, []string{testAuthHeader}, 100, 1)() + if _, ok := msg.(PlayerReadyMsg); !ok { + t.Fatalf("LaunchCmd() = %#v, want PlayerReadyMsg", msg) + } + + if position := waitPosition(t, m); position < 59 || position > 61 { + t.Errorf("GetPosition() = %.1f, want 60", position) + } +} + func TestMpvControls(t *testing.T) { srv := newAudioServer(t) m := newTestMpv(t) @@ -294,16 +311,12 @@ func TestMpvControls(t *testing.T) { t.Fatalf("Seek() error: %v", err) } waitPositionNear(t, m, 10) - if err := m.SeekRelative(5); err != nil { - t.Fatalf("SeekRelative() error: %v", err) - } - waitPositionNear(t, m, 15) if err := m.SetVolume(40); err != nil { t.Fatalf("SetVolume() error: %v", err) } - if volume, err := m.GetVolume(); err != nil || volume != 40 { - t.Errorf("GetVolume() = %d, %v, want 40", volume, err) + if volume, err := m.handle.getDouble("volume"); err != nil || volume != 40 { + t.Errorf("volume = %v, %v, want 40", volume, err) } if err := m.SetSpeed(1.5); err != nil { t.Fatalf("SetSpeed() error: %v", err) diff --git a/internal/screens/detail/model.go b/internal/screens/detail/model.go index 73b8c59..36a9315 100644 --- a/internal/screens/detail/model.go +++ b/internal/screens/detail/model.go @@ -87,9 +87,11 @@ type MarkFinishedCmd struct { Undo bool } -// MarkFinishedMsg updates the item after marking it finished. +// MarkFinishedMsg updates the item after marking it finished. EpisodeID is the +// marked episode of a podcast, or empty if the item was marked. type MarkFinishedMsg struct { - Progress *abs.UserMediaProgress + EpisodeID string + Progress *abs.UserMediaProgress } // BookmarksUpdatedMsg updates the bookmark list after a load or an @@ -232,6 +234,10 @@ type Model struct { episodes []abs.PodcastEpisode selectedEpisode int focusEpisodes bool + // finishedEpisodes holds the result of each mark of an episode on this + // screen. The progress of the podcast item is not the progress of an + // episode, and the screen does not load the progress of an episode. + finishedEpisodes map[string]bool confirm components.ConfirmOverlay } @@ -429,13 +435,11 @@ func (m Model) Init() tea.Cmd { // Update handles messages for the detail screen. func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { - if m.confirm.Visible() { - cmd, handled := m.confirm.Update(msg) - if handled { - m.refreshContent() - return m, cmd - } - return m, nil + // The dialog takes each key. Other messages, such as the result of a + // load, go on to the screen. + if cmd, handled := m.confirm.Update(msg); handled { + m.refreshContent() + return m, cmd } switch msg := msg.(type) { @@ -481,6 +485,15 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { return m, nil case MarkFinishedMsg: + if msg.Progress != nil && msg.EpisodeID != "" { + // The app also gives the message to the zero Model, before a + // detail screen opens. + if m.finishedEpisodes == nil { + m.finishedEpisodes = make(map[string]bool) + } + m.finishedEpisodes[msg.EpisodeID] = msg.Progress.IsFinished + return m, nil + } if msg.Progress != nil { m.item.UserMediaProgress = msg.Progress if m.ready { @@ -567,6 +580,9 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { episode = &ep } undo := item.UserMediaProgress != nil && item.UserMediaProgress.IsFinished + if episode != nil { + undo = m.finishedEpisodes[episode.ID] + } return m, func() tea.Msg { return MarkFinishedCmd{Item: item, Episode: episode, Undo: undo} } diff --git a/internal/screens/detail/model_test.go b/internal/screens/detail/model_test.go index 6da39e5..8e2ef08 100644 --- a/internal/screens/detail/model_test.go +++ b/internal/screens/detail/model_test.go @@ -978,6 +978,74 @@ func TestPodcastTabKey_CyclesEpisodesAndBookmarks(t *testing.T) { } } +func markFinishedPodcast() abs.LibraryItem { + return abs.LibraryItem{ + ID: "pod-001", + MediaType: "podcast", + Media: abs.Media{ + Metadata: abs.MediaMetadata{Title: "Podcast Show"}, + Episodes: []abs.PodcastEpisode{ + {ID: "ep-1", Title: "Episode One", Duration: 1800}, + {ID: "ep-2", Title: "Episode Two", Duration: 2400}, + }, + }, + } +} + +func pressMarkFinished(t *testing.T, m Model) MarkFinishedCmd { + t.Helper() + _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'f'}}) + if cmd == nil { + t.Fatal("f returned no command") + } + finish, ok := cmd().(MarkFinishedCmd) + if !ok { + t.Fatalf("f returned %T, want MarkFinishedCmd", cmd()) + } + return finish +} + +func TestMarkFinishedEpisodeIgnoresPodcastProgress(t *testing.T) { + item := markFinishedPodcast() + // The progress of the podcast item is the progress of some episode. + item.UserMediaProgress = &abs.UserMediaProgress{IsFinished: true} + m := New(ui.DefaultStyles(), item) + m.SetSize(80, 24) + m.selectedEpisode = 1 + + finish := pressMarkFinished(t, m) + if finish.Episode == nil || finish.Episode.ID != "ep-2" { + t.Fatalf("episode = %#v, want ep-2", finish.Episode) + } + if finish.Undo { + t.Fatal("Undo = true for an episode that this screen did not mark finished") + } +} + +func TestMarkFinishedEpisodeKeepsResultPerEpisode(t *testing.T) { + m := New(ui.DefaultStyles(), markFinishedPodcast()) + m.SetSize(80, 24) + + m, _ = m.Update(MarkFinishedMsg{EpisodeID: "ep-1", Progress: &abs.UserMediaProgress{IsFinished: true}}) + if m.Item().UserMediaProgress != nil { + t.Fatalf("podcast progress = %#v, want nil: the result is of one episode", m.Item().UserMediaProgress) + } + if !pressMarkFinished(t, m).Undo { + t.Fatal("Undo = false on the finished episode ep-1") + } + + m.selectedEpisode = 1 + if pressMarkFinished(t, m).Undo { + t.Fatal("Undo = true on ep-2, which is not finished") + } + + m.selectedEpisode = 0 + m, _ = m.Update(MarkFinishedMsg{EpisodeID: "ep-1", Progress: &abs.UserMediaProgress{IsFinished: false}}) + if pressMarkFinished(t, m).Undo { + t.Fatal("Undo = true on ep-1 after the undo") + } +} + func TestSetEpisodes_PreservesRecentEpisodeSelection(t *testing.T) { styles := ui.DefaultStyles() item := abs.LibraryItem{ @@ -1096,3 +1164,33 @@ func TestView_TruncatesLongEpisodeAndBookmarkTitles(t *testing.T) { t.Error("expected truncated content to contain ellipsis '...'") } } + +func TestMarkFinishedEpisodeOnZeroModel(t *testing.T) { + var m Model + m, _ = m.Update(MarkFinishedMsg{EpisodeID: "ep-1", Progress: &abs.UserMediaProgress{IsFinished: true}}) + if !m.finishedEpisodes["ep-1"] { + t.Fatal("the zero Model did not keep the result of ep-1") + } +} + +func TestConfirmDialogKeepsAsyncResults(t *testing.T) { + m := New(ui.DefaultStyles(), sampleItem()) + m.SetSize(80, 24) + m, _ = m.Update(ShowDeleteConfirmMsg{Target: "delete_item"}) + if !m.ConfirmOverlayVisible() { + t.Fatal("expected the confirmation dialog") + } + + m, _ = m.Update(BookmarksUpdatedMsg{ItemID: "li-001", Bookmarks: sampleBookmarks()}) + m, _ = m.Update(MarkFinishedMsg{Progress: &abs.UserMediaProgress{IsFinished: true}}) + + if !m.bookmarksLoaded || len(m.Bookmarks()) != len(sampleBookmarks()) { + t.Fatalf("bookmarks = %d (loaded %v), want %d", len(m.Bookmarks()), m.bookmarksLoaded, len(sampleBookmarks())) + } + if p := m.Item().UserMediaProgress; p == nil || !p.IsFinished { + t.Fatalf("progress = %#v, want finished", p) + } + if !m.ConfirmOverlayVisible() { + t.Fatal("the dialog closed without a key") + } +} diff --git a/internal/screens/home/model.go b/internal/screens/home/model.go index 9674a30..e2d5223 100644 --- a/internal/screens/home/model.go +++ b/internal/screens/home/model.go @@ -81,7 +81,7 @@ func (i listItem) FilterValue() string { parts = append(parts, author) } } - if ps := i.item.Media.Metadata.PrimarySeries(); ps != nil && ps.Name != "" { + if ps := i.item.Media.Metadata.Series; ps != nil && ps.Name != "" { parts = append(parts, ps.Name) } return strings.Join(parts, " ") @@ -218,6 +218,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { m.refreshListRows() return m, nil } + m.err = nil if len(msg.Libraries) > 0 { logger.Debug("personalized: updating libraries", "count", len(msg.Libraries)) m.libraries = msg.Libraries @@ -342,7 +343,7 @@ func (m *Model) fetchPersonalizedCmd() tea.Cmd { if err != nil { return PersonalizedMsg{Err: fmt.Errorf("fetch libraries: %w", err)} } - libs, _ = client.FilterAudioLibraries(context.Background(), libs) + libs = client.FilterAudioLibraries(context.Background(), libs) } if len(libs) == 0 { return PersonalizedMsg{Items: nil, Libraries: libs, LibraryID: currentLibID} diff --git a/internal/screens/home/model_test.go b/internal/screens/home/model_test.go index 5e952f1..f8674d7 100644 --- a/internal/screens/home/model_test.go +++ b/internal/screens/home/model_test.go @@ -210,6 +210,21 @@ func TestPersonalizedMsg_Error(t *testing.T) { } } +func TestPersonalizedMsg_SuccessClearsEarlierError(t *testing.T) { + m := newTestModel() + m.SetSize(80, 24) + + m, _ = m.Update(PersonalizedMsg{Err: fmt.Errorf("network error")}) + m, _ = m.Update(PersonalizedMsg{Items: sampleItems()}) + + if m.Error() != nil { + t.Fatalf("Error() = %v after a successful load, want nil", m.Error()) + } + if v := m.View(); strings.Contains(v, "network error") { + t.Fatalf("view still shows the earlier error:\n%s", v) + } +} + func TestEnterKey_NavigateDetail(t *testing.T) { m := newTestModel() items := sampleItems() diff --git a/internal/screens/library/model.go b/internal/screens/library/model.go index 682c7c1..6a8ea07 100644 --- a/internal/screens/library/model.go +++ b/internal/screens/library/model.go @@ -232,6 +232,7 @@ func (m *Model) tryLoadFromCache() bool { logger.Info("Library tryLoadFromCache HIT", "libraryID", m.libraryID, "items", len(items)) m.items = items m.contentLibrary = m.libraryID + m.err = nil m.loading = false m.loadingVisible = false m.totalItems = len(items) @@ -294,12 +295,18 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { m.err = msg.Err return m, nil } + m.err = nil // If this is the initial page load, but the background cache has // finished building in the meantime, prefer the full cache over the page. if msg.Page == 0 && m.tryLoadFromCache() { return m, nil } + // The full list of the cache can replace the pages while the fetch of + // a later page is in flight. That page is already in the list. + if msg.Page > 0 && len(m.items) >= m.totalItems { + return m, nil + } m.totalItems = msg.Total m.page = msg.Page @@ -429,7 +436,7 @@ func (m *Model) fetchLibraryItemsCmd(page, limit int) tea.Cmd { if err != nil { return LibraryItemsMsg{LibraryID: libraryID, Err: fmt.Errorf("fetch libraries: %w", err)} } - libs, _ = client.FilterAudioLibraries(context.Background(), libs) + libs = client.FilterAudioLibraries(context.Background(), libs) if len(libs) == 0 { return LibraryItemsMsg{Items: nil, Total: 0, Page: 0, LibraryID: libraryID} } @@ -774,7 +781,7 @@ func (i libraryListItem) FilterValue() string { parts = append(parts, author) } } - if ps := i.Item.Media.Metadata.PrimarySeries(); ps != nil && ps.Name != "" { + if ps := i.Item.Media.Metadata.Series; ps != nil && ps.Name != "" { parts = append(parts, ps.Name) } return strings.Join(parts, " ") @@ -791,7 +798,7 @@ func (m Model) TotalItems() int { } func (m Model) SelectedPaletteActions() []components.PaletteItem { - sel, ok := m.list.SelectedItem().(ListItem) + sel, ok := m.selectedItem() if !ok { return nil } @@ -807,7 +814,7 @@ func (m Model) SelectedPaletteActions() []components.PaletteItem { } if m.SelectedLibraryMediaType() == "book" { items = append(items, - components.PaletteItem{Label: "Browse Series", Action: components.ActionBrowseSeries}, + components.PaletteItem{Label: "Browse Series", Action: components.ActionBrowseSeries, LibraryID: m.SelectedLibraryID(), Payload: m.selectedLibraryName()}, ) } return items diff --git a/internal/screens/library/model_test.go b/internal/screens/library/model_test.go index 8f3e1df..e20168a 100644 --- a/internal/screens/library/model_test.go +++ b/internal/screens/library/model_test.go @@ -157,6 +157,21 @@ func TestLibraryItemsMsgError(t *testing.T) { } } +func TestLibraryItemsMsgClearsEarlierError(t *testing.T) { + m := newTestModel() + m.SetSize(80, 24) + m, _ = m.Update(LibraryItemsMsg{Items: makeItems(2), Total: 4, Page: 0}) + m, _ = m.Update(LibraryItemsMsg{Err: fmt.Errorf("network error")}) + m, _ = m.Update(LibraryItemsMsg{Items: makeItems(2), Total: 4, Page: 1}) + + if m.Error() != nil { + t.Fatalf("Error() = %v after a successful load, want nil", m.Error()) + } + if view := m.View(); containsString(view, "network error") { + t.Fatalf("view still shows the earlier error:\n%s", view) + } +} + func TestEnterEmitsNavigateDetailMsg(t *testing.T) { m := newTestModel() m.SetSize(80, 24) @@ -181,6 +196,27 @@ func TestEnterEmitsNavigateDetailMsg(t *testing.T) { } } +func TestSelectedPaletteActionsUseSelectedItem(t *testing.T) { + libs := []abs.Library{{ID: "lib-001", Name: "Books", MediaType: "book"}} + m := New(ui.DefaultStyles(), cache.NewClient(abs.NewClient("http://test", "tok"), nil), nil, "lib-001", libs) + m.SetSize(80, 24) + items := makeItems(2) + m, _ = m.Update(LibraryItemsMsg{Items: items, Total: 2, Page: 0}) + + actions := m.SelectedPaletteActions() + var labels []string + for _, action := range actions { + labels = append(labels, action.Label) + if action.Label == "Open Selected" && action.ItemID != items[0].ID { + t.Errorf("Open Selected item = %q, want %q", action.ItemID, items[0].ID) + } + } + want := []string{"Context Actions", "Open Selected", "Queue Item", "Play Next", "Browse Series"} + if strings.Join(labels, ",") != strings.Join(want, ",") { + t.Fatalf("palette actions = %v, want %v", labels, want) + } +} + func TestSKeyEmitsNavigateSeriesListMsg(t *testing.T) { libs := []abs.Library{{ID: "lib-001", Name: "Books", MediaType: "book"}} m := New(ui.DefaultStyles(), cache.NewClient(abs.NewClient("http://test", "tok"), nil), nil, "lib-001", libs) @@ -879,6 +915,62 @@ func TestLibraryItemsMsgPrefersCache(t *testing.T) { } } +func newPreparedSearchCache(t *testing.T, libraryID string, items int) *search.Cache { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if strings.HasSuffix(r.URL.Path, "/series") { + _, _ = w.Write([]byte(`{"results":[],"total":0,"limit":50,"page":0}`)) + return + } + results := make([]string, items) + for i := range results { + results[i] = fmt.Sprintf(`{"id":"item-%d","libraryId":%q,"mediaType":"book","media":{"metadata":{"title":"Book %d"}}}`, i, libraryID, i) + } + _, _ = fmt.Fprintf(w, `{"results":[%s],"total":%d,"limit":50,"page":0}`, strings.Join(results, ","), items) + })) + t.Cleanup(srv.Close) + return search.NewCache(cache.NewClient(abs.NewClient(srv.URL, "tok"), nil), nil) +} + +func TestSearchCacheReadyClearsEarlierError(t *testing.T) { + c := newPreparedSearchCache(t, "lib-001", 2) + libs := []abs.Library{{ID: "lib-001", MediaType: "book"}} + m := New(ui.DefaultStyles(), nil, c, "lib-001", libs) + m, _ = m.Update(LibraryItemsMsg{LibraryID: "lib-001", Err: fmt.Errorf("network error")}) + + if err := c.Prepare(context.Background(), "lib-001", "book"); err != nil { + t.Fatalf("Prepare: %v", err) + } + m, _ = m.Update(search.CacheReadyMsg{LibraryID: "lib-001"}) + + if m.Error() != nil { + t.Fatalf("Error() = %v after the cache load, want nil", m.Error()) + } + if len(m.Items()) != 2 { + t.Fatalf("items = %d, want 2", len(m.Items())) + } +} + +func TestLatePageAfterCacheLoadIsDropped(t *testing.T) { + c := newPreparedSearchCache(t, "lib-001", 4) + libs := []abs.Library{{ID: "lib-001", MediaType: "book"}} + m := New(ui.DefaultStyles(), nil, c, "lib-001", libs) + + // Page 0 comes from the server before the search cache is ready. + m, _ = m.Update(LibraryItemsMsg{Items: makeItems(2), Total: 4, Page: 0, LibraryID: "lib-001"}) + // The search cache gets ready while the fetch of page 1 is in flight. + if err := c.Prepare(context.Background(), "lib-001", "book"); err != nil { + t.Fatalf("Prepare: %v", err) + } + m, _ = m.Update(search.CacheReadyMsg{LibraryID: "lib-001"}) + m, _ = m.Update(LibraryItemsMsg{Items: makeItems(4)[2:], Total: 4, Page: 1, LibraryID: "lib-001"}) + + if len(m.Items()) != 4 { + t.Fatalf("items = %d, want the 4 items of the cache", len(m.Items())) + } +} + func TestNextLibTriggersPrebuild(t *testing.T) { libs := []abs.Library{ {ID: "lib-1", Name: "Books", MediaType: "book"}, diff --git a/internal/screens/metadataedit/model.go b/internal/screens/metadataedit/model.go index b2e9686..489d187 100644 --- a/internal/screens/metadataedit/model.go +++ b/internal/screens/metadataedit/model.go @@ -3,6 +3,7 @@ package metadataedit import ( "strings" "sync/atomic" + "unicode/utf8" "github.com/Thelost77/pine/internal/abs" "github.com/Thelost77/pine/internal/ui" @@ -65,7 +66,11 @@ type Model struct { episode *abs.PodcastEpisode generation uint64 - inputs [numFields]textinput.Model + inputs [numFields]textinput.Model + // initial holds the value of each input before an edit. A field changes + // only if its input differs from it. The input puts a space for a + // newline or a tab, so its value can differ from the value of ABS. + initial [numFields]string focused int authorEditable bool @@ -87,7 +92,7 @@ func New(styles ui.Styles, item abs.LibraryItem) Model { inputs[fieldTitle] = newInput("Title", meta.Title, 256) inputs[fieldAuthor] = newInput("Author", initialAuthorValue(meta), 256) - series := meta.PrimarySeries() + series := meta.Series seriesName := "" seriesSequence := "" if series != nil { @@ -106,6 +111,7 @@ func New(styles ui.Styles, item abs.LibraryItem) Model { seriesEditable: item.MediaType == "book" && !meta.HasMultipleSeries(), styles: styles, } + m.setInitialValues() _ = m.updateFocus() return m } @@ -127,19 +133,35 @@ func NewEpisode(styles ui.Styles, item abs.LibraryItem, episode abs.PodcastEpiso focused: fieldTitle, styles: styles, } + m.setInitialValues() _ = m.updateFocus() return m } +// newInput makes an input for value. The input takes at least the whole value, +// so that an edit does not cut a long value. func newInput(placeholder, value string, limit int) textinput.Model { input := textinput.New() input.Placeholder = placeholder - input.CharLimit = limit + input.CharLimit = max(limit, utf8.RuneCountInString(value)) input.Prompt = "" input.SetValue(value) return input } +func (m *Model) setInitialValues() { + for i := range m.inputs { + m.initial[i] = m.inputs[i].Value() + } +} + +// fieldValue returns the trimmed value of a field, and whether the user +// changed it. +func (m Model) fieldValue(field int) (string, bool) { + value := strings.TrimSpace(m.inputs[field].Value()) + return value, value != strings.TrimSpace(m.initial[field]) +} + // Init returns the initial command. func (m Model) Init() tea.Cmd { return textinput.Blink @@ -187,8 +209,10 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { if !m.fieldEditable(m.focused) { return m, nil } - m.validationErr = "" - m.saveErr = nil + if _, ok := msg.(tea.KeyMsg); ok { + m.validationErr = "" + m.saveErr = nil + } var cmd tea.Cmd m.inputs[m.focused], cmd = m.inputs[m.focused].Update(msg) return m, cmd @@ -236,15 +260,14 @@ func (m Model) saveEpisode() (Model, tea.Cmd) { } func (m Model) buildRequest() (abs.UpdateMediaRequest, bool, string) { - meta := m.item.Media.Metadata request := abs.UpdateMediaRequest{} changed := false - title := strings.TrimSpace(m.inputs[fieldTitle].Value()) + title, titleChanged := m.fieldValue(fieldTitle) if title == "" { return request, false, "Title cannot be empty" } - if title != strings.TrimSpace(meta.Title) { + if titleChanged { request.Metadata.Title = &title changed = true } @@ -276,32 +299,28 @@ func (m Model) buildEpisodeRequest() (abs.UpdatePodcastEpisodeRequest, bool, str return request, false, "No episode selected" } - title := strings.TrimSpace(m.inputs[fieldTitle].Value()) + title, titleChanged := m.fieldValue(fieldTitle) if title == "" { return request, false, "Title cannot be empty" } - if title != strings.TrimSpace(episode.Title) { + if titleChanged { request.Title = &title changed = true } - description := strings.TrimSpace(m.inputs[fieldDescription].Value()) - if description != strings.TrimSpace(episode.Description) { + if description, ok := m.fieldValue(fieldDescription); ok { request.Description = &description changed = true } - season := strings.TrimSpace(m.inputs[fieldSeason].Value()) - if season != strings.TrimSpace(episode.Season) { + if season, ok := m.fieldValue(fieldSeason); ok { request.Season = &season changed = true } - episodeNumber := strings.TrimSpace(m.inputs[fieldEpisode].Value()) - if episodeNumber != strings.TrimSpace(episode.Episode) { + if episodeNumber, ok := m.fieldValue(fieldEpisode); ok { request.Episode = &episodeNumber changed = true } - episodeType := strings.TrimSpace(m.inputs[fieldEpisodeType].Value()) - if episodeType != strings.TrimSpace(episode.EpisodeType) { + if episodeType, ok := m.fieldValue(fieldEpisodeType); ok { request.EpisodeType = &episodeType changed = true } @@ -310,13 +329,8 @@ func (m Model) buildEpisodeRequest() (abs.UpdatePodcastEpisodeRequest, bool, str } func (m Model) buildAuthors() ([]abs.Author, bool) { - newName := strings.TrimSpace(m.inputs[fieldAuthor].Value()) - original, ok := singleAuthor(m.item.Media.Metadata) - originalName := "" - if ok { - originalName = strings.TrimSpace(original.Name) - } - if newName == originalName { + newName, changed := m.fieldValue(fieldAuthor) + if !changed { return nil, false } if newName == "" { @@ -326,15 +340,12 @@ func (m Model) buildAuthors() ([]abs.Author, bool) { } func (m Model) buildSeries() ([]abs.SeriesSequence, bool) { - newName := strings.TrimSpace(m.inputs[fieldSeries].Value()) - newSequence := strings.TrimSpace(m.inputs[fieldSequence].Value()) - original, ok := singleSeries(m.item.Media.Metadata) - if ok && newName == strings.TrimSpace(original.Name) && newSequence == strings.TrimSpace(original.Sequence) { - return nil, false - } - if !ok && newName == "" && newSequence == "" { + newName, nameChanged := m.fieldValue(fieldSeries) + newSequence, sequenceChanged := m.fieldValue(fieldSequence) + if !nameChanged && !sequenceChanged { return nil, false } + original, ok := singleSeries(m.item.Media.Metadata) if newName == "" { return []abs.SeriesSequence{}, true } diff --git a/internal/screens/metadataedit/model_test.go b/internal/screens/metadataedit/model_test.go index 04d8d1f..cfbf8ba 100644 --- a/internal/screens/metadataedit/model_test.go +++ b/internal/screens/metadataedit/model_test.go @@ -2,11 +2,13 @@ package metadataedit import ( "errors" + "strings" "testing" "github.com/Thelost77/pine/internal/abs" "github.com/Thelost77/pine/internal/config" "github.com/Thelost77/pine/internal/ui" + "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" ) @@ -65,6 +67,7 @@ func TestBuildRequestChangedSeriesNameOmitsOldID(t *testing.T) { MediaType: "book", Media: abs.Media{Metadata: abs.MediaMetadata{ Title: "Title", + Series: &abs.SeriesSequence{ID: "series-1", Name: "Old Series", Sequence: "1"}, SeriesList: []abs.SeriesSequence{{ID: "series-1", Name: "Old Series", Sequence: "1"}}, }}, } @@ -225,6 +228,7 @@ func TestBuildRequestClearsSeries(t *testing.T) { MediaType: "book", Media: abs.Media{Metadata: abs.MediaMetadata{ Title: "Title", + Series: &abs.SeriesSequence{ID: "series-1", Name: "Old Series", Sequence: "1"}, SeriesList: []abs.SeriesSequence{{ID: "series-1", Name: "Old Series", Sequence: "1"}}, }}, } @@ -248,6 +252,7 @@ func TestMultiAuthorAndSeriesFieldsAreReadOnly(t *testing.T) { Media: abs.Media{Metadata: abs.MediaMetadata{ Title: "Title", Authors: []abs.Author{{Name: "One"}, {Name: "Two"}}, + Series: &abs.SeriesSequence{Name: "One"}, SeriesList: []abs.SeriesSequence{{Name: "One"}, {Name: "Two"}}, }}, } @@ -319,3 +324,75 @@ func TestSavedMsgStoresSaveError(t *testing.T) { t.Fatalf("SaveError() = %v, want %v", m.SaveError(), err) } } + +func TestSaveKeepsUntouchedFieldsThatTheInputChanges(t *testing.T) { + long := strings.Repeat("show notes ", 300) + episode := abs.PodcastEpisode{ + ID: "ep-1", + Title: "Episode", + Description: "Line one\nLine two\t" + long, + Season: "1", + } + item := abs.LibraryItem{ID: "pod-1", MediaType: "podcast", Media: abs.Media{Metadata: abs.MediaMetadata{Title: "Podcast"}}} + + m := NewEpisode(testStyles(), item, episode) + if _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}); cmd == nil { + t.Fatal("enter returned no command") + } else if msg := cmd(); msg != (BackMsg{}) { + t.Fatalf("enter with no edit returned %T, want BackMsg", msg) + } + + m.inputs[fieldTitle].SetValue("New Episode") + req, changed, errText := m.buildEpisodeRequest() + if errText != "" || !changed { + t.Fatalf("buildEpisodeRequest changed=%v err=%q", changed, errText) + } + if req.Description != nil { + t.Fatalf("Description = %.40q..., want nil: the user did not edit it", *req.Description) + } + + book := abs.LibraryItem{ID: "item-1", MediaType: "book", Media: abs.Media{Metadata: abs.MediaMetadata{ + Title: "Title\nSubtitle " + strings.Repeat("x", 300), + Authors: []abs.Author{{Name: "Ann\tAuthor"}}, + Series: &abs.SeriesSequence{ID: "series-1", Name: "Saga\nOne", Sequence: "1"}, + }}} + if _, changed, errText := New(testStyles(), book).buildRequest(); errText != "" || changed { + t.Fatalf("book buildRequest changed=%v err=%q, want no change", changed, errText) + } +} + +func TestEditKeepsTheLongValue(t *testing.T) { + long := strings.Repeat("d", 2500) + m := NewEpisode(testStyles(), abs.LibraryItem{ID: "pod-1", MediaType: "podcast"}, abs.PodcastEpisode{ID: "ep-1", Title: "Episode", Description: long}) + m.focused = fieldDescription + _ = m.updateFocus() + + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyBackspace}) + req, _, _ := m.buildEpisodeRequest() + if req.Description == nil || *req.Description != long[:len(long)-1] { + t.Fatal("the edit of the description cut the text") + } +} + +func TestBlinkKeepsErrors(t *testing.T) { + m := New(testStyles(), abs.LibraryItem{ID: "item-1", MediaType: "book", Media: abs.Media{Metadata: abs.MediaMetadata{Title: "Title"}}}) + m.inputs[fieldTitle].SetValue("") + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m, _ = m.Update(SavedMsg{ItemID: "item-1", Err: errors.New("forbidden")}) + if m.ValidationError() == "" || m.SaveError() == nil { + t.Fatal("expected a validation error and a save error") + } + + m, _ = m.Update(textinput.Blink()) + if m.ValidationError() == "" { + t.Fatal("the blink of the cursor cleared the validation error") + } + if m.SaveError() == nil { + t.Fatal("the blink of the cursor cleared the save error") + } + + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'T'}}) + if m.ValidationError() != "" || m.SaveError() != nil { + t.Fatal("an edit did not clear the errors") + } +} diff --git a/internal/screens/search/cache.go b/internal/screens/search/cache.go index 045d3c8..1647220 100644 --- a/internal/screens/search/cache.go +++ b/internal/screens/search/cache.go @@ -116,7 +116,10 @@ type Cache struct { mu sync.Mutex snapshots map[string]*librarySnapshot - builds map[string]*snapshotBuild + // builds holds the build in flight of each library. An invalidation + // removes the build: its data can be from before the change, so it + // stores nothing. + builds map[string]*snapshotBuild } type snapshotBuild struct { @@ -169,8 +172,16 @@ func NewCache(client *cache.Client, store *cache.Store) *Cache { if client != nil { client.OnInvalidate = func() { c.mu.Lock() + defer c.mu.Unlock() + // The client clears the store before it calls this function. A + // build can store its snapshot between the two steps. + if c.store != nil { + for libraryID := range c.snapshots { + _ = c.store.Delete(cache.SearchSnapshotKey(libraryID)) + } + } c.snapshots = make(map[string]*librarySnapshot) - c.mu.Unlock() + c.builds = make(map[string]*snapshotBuild) } } return c @@ -183,41 +194,10 @@ func (c *Cache) Invalidate(libraryID string) { } c.mu.Lock() delete(c.snapshots, libraryID) + delete(c.builds, libraryID) c.mu.Unlock() } -// UpdateItem replaces cached metadata for a single item in-place. -// This avoids a full re-fetch from ABS which can return stale data. -func (c *Cache) UpdateItem(item abs.LibraryItem) { - if c == nil || item.LibraryID == "" { - return - } - c.mu.Lock() - defer c.mu.Unlock() - snap, ok := c.snapshots[item.LibraryID] - if !ok { - return - } - title := item.Media.Metadata.Title - author := item.Media.Metadata.DisplayAuthor() - if author == "Unknown author" { - author = "" - } - for i, e := range snap.entries { - if e.itemID == item.ID { - snap.entries[i].title = title - snap.entries[i].author = author - snap.entries[i].primarySearchText = normalizeSearchText(title) - snap.entries[i].secondarySearchText = normalizeSearchText(author) - snap.entries[i].combinedSearchText = combineSearchText(title, author) - snap.entries[i].fuzzySearchText = compactNormalizedText(combineSearchText(title, author)) - snap.entries[i].primaryTokens = tokenizeSearchText(normalizeSearchText(title)) - snap.entries[i].combinedTokens = tokenizeSearchText(combineSearchText(title, author)) - return - } - } -} - // Prepare ensures the library snapshot exists before the user starts searching. func (c *Cache) Prepare(ctx context.Context, libraryID, libraryMediaType string) error { if _, err := c.ensureSnapshot(ctx, libraryID, libraryMediaType); err != nil { @@ -245,16 +225,29 @@ func (c *Cache) PrebuildCmd(libraryID, libraryMediaType string) tea.Cmd { } } -// Search returns search results from a cached per-library snapshot. -func (c *Cache) Search(ctx context.Context, libraryID, libraryMediaType, query string) ([]abs.LibraryItem, error) { +// Search returns search results from the cached snapshot of a library. The +// command palette calls it in the Update loop, so it does not wait for the +// network: if no snapshot is ready, it returns no results and builds the +// snapshot in the background. +func (c *Cache) Search(_ context.Context, libraryID, libraryMediaType, query string) ([]abs.LibraryItem, error) { normalized := normalizeQuery(query) if normalized == "" { return nil, nil } + if c == nil || c.client == nil { + return nil, fmt.Errorf("not authenticated") + } - snapshot, err := c.ensureSnapshot(ctx, libraryID, libraryMediaType) - if err != nil { - return nil, err + c.mu.Lock() + snapshot, ok := c.readySnapshot(libraryID, libraryMediaType) + c.mu.Unlock() + if !ok { + go func() { + if err := c.Prepare(context.Background(), libraryID, libraryMediaType); err != nil { + logger.Warn("search snapshot build failed", "libraryID", libraryID, "err", err) + } + }() + return nil, nil } return snapshot.filter(normalized), nil @@ -269,14 +262,23 @@ func (c *Cache) TryGetAll(libraryID, libraryMediaType string) ([]abs.LibraryItem c.mu.Lock() defer c.mu.Unlock() + snapshot, ok := c.readySnapshot(libraryID, libraryMediaType) + if !ok { + return nil, false + } + return snapshot.items, true +} +// readySnapshot returns the snapshot of a library from memory or from the +// store, with no network request. The caller holds c.mu. +func (c *Cache) readySnapshot(libraryID, libraryMediaType string) (*librarySnapshot, bool) { resolvedID, resolvedMediaType := libraryID, libraryMediaType // Best effort without blocking // 1. Check in-memory cache if snapshot, ok := c.snapshots[resolvedID]; ok { if c.now().Sub(snapshot.builtAt) <= c.ttl && snapshot.mediaType == resolvedMediaType { snapshot.lastAccessedAt = c.now() - return snapshot.items, true + return snapshot, true } } @@ -296,7 +298,7 @@ func (c *Cache) TryGetAll(libraryID, libraryMediaType string) ([]abs.LibraryItem items: persisted.Items, } c.snapshots[resolvedID] = snapshot - return snapshot.items, true + return snapshot, true } } } @@ -366,6 +368,16 @@ func (c *Cache) ensureSnapshot(ctx context.Context, libraryID, libraryMediaType if err == nil { snapshot.builtAt = now snapshot.lastAccessedAt = now + } + + // The check of the build and the writes are one step under c.mu, so an + // invalidation comes before or after both. + c.mu.Lock() + current := c.builds[resolvedID] == build + if current { + delete(c.builds, resolvedID) + } + if err == nil && current { // Persist to disk cache if c.store != nil { persistedEntries := make([]PersistedEntry, len(snapshot.entries)) @@ -381,11 +393,6 @@ func (c *Cache) ensureSnapshot(ctx context.Context, libraryID, libraryMediaType Items: snapshot.items, }, c.ttl) } - } - - c.mu.Lock() - delete(c.builds, resolvedID) - if err == nil { c.snapshots[resolvedID] = snapshot } build.snapshot = snapshot @@ -617,7 +624,7 @@ func (c *Cache) resolveLibrary(ctx context.Context, libraryID, libraryMediaType if err != nil { return "", "", fmt.Errorf("fetch libraries: %w", err) } - libs, _ = c.client.FilterAudioLibraries(ctx, libs) + libs = c.client.FilterAudioLibraries(ctx, libs) if len(libs) == 0 { return "", "", nil } diff --git a/internal/screens/search/cache_test.go b/internal/screens/search/cache_test.go index 63d8c5f..afa4da9 100644 --- a/internal/screens/search/cache_test.go +++ b/internal/screens/search/cache_test.go @@ -6,6 +6,7 @@ import ( "net/http" "net/http/httptest" "path/filepath" + "sync" "testing" "time" @@ -51,6 +52,9 @@ func TestCacheReusesPodcastSnapshotAcrossQueries(t *testing.T) { defer srv.Close() cache := NewCache(cache.NewClient(abs.NewClient(srv.URL, "tok"), nil), nil) + if err := cache.Prepare(context.Background(), "lib-pod", "podcast"); err != nil { + t.Fatalf("Prepare() error: %v", err) + } first, err := cache.Search(context.Background(), "lib-pod", "podcast", "Joe") if err != nil { @@ -118,14 +122,14 @@ func TestCacheKeepsSnapshotsPerLibraryID(t *testing.T) { cache := NewCache(cache.NewClient(abs.NewClient(srv.URL, "tok"), nil), nil) - if _, err := cache.Search(context.Background(), "lib-a", "book", "alp"); err != nil { - t.Fatalf("search lib-a: %v", err) + if err := cache.Prepare(context.Background(), "lib-a", "book"); err != nil { + t.Fatalf("prepare lib-a: %v", err) } - if _, err := cache.Search(context.Background(), "lib-b", "book", "bet"); err != nil { - t.Fatalf("search lib-b: %v", err) + if err := cache.Prepare(context.Background(), "lib-b", "book"); err != nil { + t.Fatalf("prepare lib-b: %v", err) } - if _, err := cache.Search(context.Background(), "lib-a", "book", "ann"); err != nil { - t.Fatalf("search lib-a again: %v", err) + if results, err := cache.Search(context.Background(), "lib-a", "book", "ann"); err != nil || len(results) != 1 { + t.Fatalf("search lib-a again = %d results, err %v; want 1", len(results), err) } if calls["lib-a"] != 1 { @@ -164,12 +168,12 @@ func TestCacheRebuildsStaleSnapshot(t *testing.T) { cache.ttl = time.Minute cache.now = func() time.Time { return now } - if _, err := cache.Search(context.Background(), "lib-a", "book", "alp"); err != nil { - t.Fatalf("first search: %v", err) + if err := cache.Prepare(context.Background(), "lib-a", "book"); err != nil { + t.Fatalf("first prepare: %v", err) } now = now.Add(2 * time.Minute) - if _, err := cache.Search(context.Background(), "lib-a", "book", "alp"); err != nil { - t.Fatalf("second search: %v", err) + if err := cache.Prepare(context.Background(), "lib-a", "book"); err != nil { + t.Fatalf("second prepare: %v", err) } if listCalls != 2 { @@ -239,6 +243,9 @@ func TestCachePodcastSearchMatchesNumericTokenAfterPunctuation(t *testing.T) { defer srv.Close() cache := NewCache(cache.NewClient(abs.NewClient(srv.URL, "tok"), nil), nil) + if err := cache.Prepare(context.Background(), "lib-pod", "podcast"); err != nil { + t.Fatalf("Prepare() error: %v", err) + } results, err := cache.Search(context.Background(), "lib-pod", "podcast", "100") if err != nil { @@ -276,6 +283,9 @@ func TestCacheBookSearchUsesFuzzyFallback(t *testing.T) { defer srv.Close() cache := NewCache(cache.NewClient(abs.NewClient(srv.URL, "tok"), nil), nil) + if err := cache.Prepare(context.Background(), "lib-a", "book"); err != nil { + t.Fatalf("Prepare() error: %v", err) + } results, err := cache.Search(context.Background(), "lib-a", "book", "tgg") if err != nil { @@ -332,6 +342,9 @@ func TestCachePersistsSnapshotToDiskAndRestoresOnRestart(t *testing.T) { // Build snapshot with first cache instance firstCache := NewCache(client, cacheStore) + if err := firstCache.Prepare(context.Background(), "lib-a", "book"); err != nil { + t.Fatalf("first prepare: %v", err) + } results1, err := firstCache.Search(context.Background(), "lib-a", "book", "alp") if err != nil { t.Fatalf("first search: %v", err) @@ -419,3 +432,144 @@ func TestBuildSnapshotPagination(t *testing.T) { t.Fatalf("expected 100 items in cache, got %d", len(items)) } } + +// blockingLibraryServer serves lib-1 with one book. The first request for the +// items waits until release is closed and gives the title "Old Title". Each +// later request gives "New Title" at once. +func blockingLibraryServer(t *testing.T, started chan<- struct{}, release <-chan struct{}) *httptest.Server { + t.Helper() + var mu sync.Mutex + itemCalls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodDelete && r.URL.Path == "/api/items/book-1": + _, _ = w.Write([]byte(`{}`)) + case r.URL.Path == "/api/libraries/lib-1/series": + _, _ = w.Write([]byte(`{"results":[],"total":0,"limit":50,"page":0}`)) + case r.URL.Path == "/api/libraries/lib-1/items": + mu.Lock() + itemCalls++ + first := itemCalls == 1 + mu.Unlock() + title := "New Title" + if first { + started <- struct{}{} + <-release + title = "Old Title" + } + _, _ = fmt.Fprintf(w, `{"results":[{"id":"book-1","libraryId":"lib-1","mediaType":"book","media":{"metadata":{"title":%q}}}],"total":1,"limit":50,"page":0}`, title) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + } + })) + t.Cleanup(srv.Close) + return srv +} + +func TestSearchDoesNotWaitForTheNetwork(t *testing.T) { + started := make(chan struct{}, 1) + release := make(chan struct{}) + srv := blockingLibraryServer(t, started, release) + c := NewCache(cache.NewClient(abs.NewClient(srv.URL, "tok"), nil), nil) + + searched := make(chan []abs.LibraryItem, 1) + go func() { + results, _ := c.Search(context.Background(), "lib-1", "book", "title") + searched <- results + }() + select { + case results := <-searched: + if len(results) != 0 { + t.Fatalf("results = %d with no snapshot, want 0", len(results)) + } + case <-time.After(2 * time.Second): + close(release) + t.Fatal("Search waited for the network") + } + + // The search started a build in the background. + select { + case <-started: + case <-time.After(2 * time.Second): + t.Fatal("Search started no build") + } + close(release) + if err := c.Prepare(context.Background(), "lib-1", "book"); err != nil { + t.Fatalf("Prepare: %v", err) + } + results, err := c.Search(context.Background(), "lib-1", "book", "title") + if err != nil || len(results) != 1 { + t.Fatalf("Search after the build = %d results, err %v; want 1", len(results), err) + } +} + +func TestInvalidationDiscardsBuildInFlight(t *testing.T) { + started := make(chan struct{}, 1) + release := make(chan struct{}) + srv := blockingLibraryServer(t, started, release) + + dbStore, err := db.Open(filepath.Join(t.TempDir(), "test.db")) + if err != nil { + t.Fatalf("open db: %v", err) + } + t.Cleanup(func() { _ = dbStore.Close() }) + store := cache.NewStore(dbStore) + client := cache.NewClient(abs.NewClient(srv.URL, "tok"), store) + c := NewCache(client, store) + + oldBuild := make(chan error, 1) + go func() { oldBuild <- c.Prepare(context.Background(), "lib-1", "book") }() + <-started + + // The delete changes the library while the build reads it. + if err := client.DeleteItem(context.Background(), "book-1", false); err != nil { + t.Fatalf("DeleteItem: %v", err) + } + newBuild := make(chan error, 1) + go func() { newBuild <- c.Prepare(context.Background(), "lib-1", "book") }() + select { + case err := <-newBuild: + if err != nil { + t.Fatalf("Prepare after the delete: %v", err) + } + case <-time.After(2 * time.Second): + t.Error("Prepare after the delete waited for the build from before the delete") + } + close(release) + if err := <-oldBuild; err != nil { + t.Fatalf("old build: %v", err) + } + + for name, cc := range map[string]*Cache{"memory": c, "disk": NewCache(client, store)} { + items, ok := cc.TryGetAll("lib-1", "book") + if !ok || len(items) != 1 || items[0].Media.Metadata.Title != "New Title" { + t.Errorf("%s: snapshot = %#v (ok %v), want the one book with New Title", name, items, ok) + } + } +} + +func TestInvalidationRemovesSnapshotStoredBeforeTheHook(t *testing.T) { + release := make(chan struct{}) + close(release) + srv := blockingLibraryServer(t, make(chan struct{}, 1), release) + dbStore, err := db.Open(filepath.Join(t.TempDir(), "test.db")) + if err != nil { + t.Fatalf("open db: %v", err) + } + t.Cleanup(func() { _ = dbStore.Close() }) + store := cache.NewStore(dbStore) + client := cache.NewClient(abs.NewClient(srv.URL, "tok"), store) + c := NewCache(client, store) + + // The client clears the store and then calls OnInvalidate. A build can + // store its snapshot between the two steps, as this Prepare does. + if err := c.Prepare(context.Background(), "lib-1", "book"); err != nil { + t.Fatalf("Prepare: %v", err) + } + client.OnInvalidate() + + if _, ok := NewCache(client, store).TryGetAll("lib-1", "book"); ok { + t.Fatal("the store keeps the snapshot after OnInvalidate") + } +} diff --git a/internal/screens/serieslist/model.go b/internal/screens/serieslist/model.go index 36f60bd..ec19f47 100644 --- a/internal/screens/serieslist/model.go +++ b/internal/screens/serieslist/model.go @@ -118,6 +118,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { m.err = msg.Err return m, nil } + m.err = nil m.total = msg.Total m.page = msg.Page if msg.Page == 0 { diff --git a/internal/screens/serieslist/model_test.go b/internal/screens/serieslist/model_test.go index 57c74c6..23dc91f 100644 --- a/internal/screens/serieslist/model_test.go +++ b/internal/screens/serieslist/model_test.go @@ -1,6 +1,7 @@ package serieslist import ( + "errors" "strings" "testing" @@ -35,6 +36,20 @@ func TestLoadedMsgPopulatesList(t *testing.T) { } } +func TestLoadedMsgClearsEarlierError(t *testing.T) { + m := newTestModel() + m, _ = m.Update(LoadedMsg{Results: sampleSeries(), Total: 4, Page: 0}) + m, _ = m.Update(LoadedMsg{Err: errors.New("network error")}) + m, _ = m.Update(LoadedMsg{Results: []abs.Series{{ID: "series-foundation", Name: "Foundation"}}, Total: 4, Page: 1}) + + if m.err != nil { + t.Fatalf("err = %v after a successful load, want nil", m.err) + } + if v := m.View(); !strings.Contains(v, "Foundation") { + t.Fatalf("expected view to show the loaded series\n%s", v) + } +} + func TestViewShowsSeriesNames(t *testing.T) { m := newTestModel() m, _ = m.Update(LoadedMsg{Results: sampleSeries(), Total: 2, Page: 0}) diff --git a/internal/spruce/app/e2e_test.go b/internal/spruce/app/e2e_test.go index 5e968b2..090dafe 100644 --- a/internal/spruce/app/e2e_test.go +++ b/internal/spruce/app/e2e_test.go @@ -15,6 +15,7 @@ import ( "github.com/Thelost77/pine/internal/spruce/jellyfin" "github.com/Thelost77/pine/internal/spruce/screens/library" "github.com/Thelost77/pine/internal/spruce/screens/login" + "github.com/Thelost77/pine/internal/spruce/screens/queue" tea "github.com/charmbracelet/bubbletea" ) @@ -464,6 +465,65 @@ func TestE2E(t *testing.T) { } }) + t.Run("G8_track_change_reports_previous_track_stopped", func(t *testing.T) { + mj := newMockJellyfin(t, 2) + m := New(nil, nil) + m.SetSize(80, 24) + + tracks := []jellyfin.Track{ + {ID: "trk-0", Name: "Track Zero", RunTimeTicks: 180 * 1e7, Artists: []string{"Artist A"}}, + {ID: "trk-1", Name: "Track One", RunTimeTicks: 200 * 1e7, Artists: []string{"Artist A"}}, + } + m, _ = driveToPlayback(mj, tracks, 0)(t, m) + firstSession := m.playSessionID + m.playerState.Position = 179 + + m, cmd := update(m, player.PlayerEndMsg{Generation: m.playGeneration, Reason: "eof"}) + execCmd(m, cmd) + + stopped := mj.stoppedCalls() + if len(stopped) != 1 { + t.Fatalf("expected 1 POST /Sessions/Playing/Stopped, got %d", len(stopped)) + } + var req jellyfin.PlaybackProgressRequest + if err := json.Unmarshal([]byte(stopped[0]), &req); err != nil { + t.Fatalf("unmarshal stopped body: %v", err) + } + if req.ItemID != "trk-0" || req.PlaySessionId != firstSession || req.PositionTicks != 179*1e7 { + t.Errorf("stopped report = %+v, want trk-0 at 179 s in session %q", req, firstSession) + } + if started := mj.startedCalls(); len(started) != 2 { + t.Errorf("expected 2 POST /Sessions/Playing, got %d", len(started)) + } + }) + + t.Run("G9_clear_queue_reports_stopped", func(t *testing.T) { + mj := newMockJellyfin(t, 1) + m := New(nil, nil) + m.SetSize(80, 24) + + tracks := []jellyfin.Track{ + {ID: "trk-0", Name: "Track Zero", RunTimeTicks: 180 * 1e7, Artists: []string{"Artist A"}}, + } + m, _ = driveToPlayback(mj, tracks, 0)(t, m) + m.playerState.Position = 42 + + m, cmd := update(m, queue.QueueActionMsg{Action: "clear"}) + execCmd(m, cmd) + + stopped := mj.stoppedCalls() + if len(stopped) != 1 { + t.Fatalf("expected 1 POST /Sessions/Playing/Stopped, got %d", len(stopped)) + } + var req jellyfin.PlaybackProgressRequest + if err := json.Unmarshal([]byte(stopped[0]), &req); err != nil { + t.Fatalf("unmarshal stopped body: %v", err) + } + if req.ItemID != "trk-0" || req.PositionTicks != 42*1e7 { + t.Errorf("stopped report = %+v, want trk-0 at 42 s", req) + } + }) + t.Run("Help_overlay_toggle", func(t *testing.T) { m := New(nil, nil) m.SetSize(80, 24) diff --git a/internal/spruce/app/help.go b/internal/spruce/app/help.go index 30fc797..2980057 100644 --- a/internal/spruce/app/help.go +++ b/internal/spruce/app/help.go @@ -66,7 +66,7 @@ func helpGroups() []components.HelpGroup { {Key: "-", Desc: "speed down"}, {Key: "] / [", Desc: "volume up / down"}, {Key: "s", Desc: "shuffle"}, - {Key: "S", Desc: "sleep timer"}, + {Key: "S", Desc: "sleep timer (queue)"}, }, }, } diff --git a/internal/spruce/app/model.go b/internal/spruce/app/model.go index 70bb211..68b0118 100644 --- a/internal/spruce/app/model.go +++ b/internal/spruce/app/model.go @@ -80,8 +80,9 @@ type Model struct { playGeneration uint64 playSessionID string - lastHeartbeat time.Time - lastMprisEmit time.Time + // playItemID is the item of the open Jellyfin play session, or "". + playItemID string + lastHeartbeat time.Time sleepDeadline time.Time sleepDuration time.Duration @@ -307,9 +308,12 @@ func (m *Model) handleAuthReset(err error) (tea.Model, tea.Cmd) { m.mediaCancel = nil m.mediaContext = nil } + // The next login can be for a different user or server, so the screens + // load their content again. + m.libraryScreen = library.New(m.styles) + m.playlistsScreen = playlists.New(m.styles) m.syncQueueScreen() m.client = nil - m.playlistsScreen.SetClient(nil) m.screen = ScreenLogin return m, tea.Batch(stopCmd, m.err.SetError(err), m.loginScreen.Init()) } @@ -399,7 +403,8 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { newM, stopCmd := m.stopAllPlayback() return newM, tea.Batch(stopCmd, tea.Quit) } - if m.isSubliminalRunning() { + screenKey := m.isScreenKey(msg) + if m.isSubliminalRunning() && !screenKey { if key.Matches(msg, m.keys.SleepTimer) { return m.cycleSleepTimer() } @@ -413,7 +418,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.setSubliminalPaused(m.playerState.Playing) } } - if m.IsPlaying() { + if m.IsPlaying() && !screenKey { if key.Matches(msg, m.keys.SleepTimer) { return m.cycleSleepTimer() } @@ -432,19 +437,10 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.handleSeek(-seek) } if key.Matches(msg, m.keys.NextTrack) { - if len(m.tracks) > 0 && m.currentIndex+1 < len(m.tracks) { - return m.startPlaybackAt(m.nextIndex(m.currentIndex + 1)) - } - return m, nil + return m.playNext() } if key.Matches(msg, m.keys.PrevTrack) { - if m.playerState.Position > 3.0 { - return m.handleSeek(-m.playerState.Position) - } - if len(m.tracks) > 0 && m.currentIndex-1 >= 0 { - return m.startPlaybackAt(m.currentIndex - 1) - } - return m, nil + return m.playPrevious() } if key.Matches(msg, m.keys.RepeatTrack) { return m.Update(queue.QueueActionMsg{ @@ -532,7 +528,9 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } } m.libraryScreen.PatchTrack(msg.ItemID, msg.Req.Name, msg.Req.Artists, msg.Req.Album) + albumCmd := m.libraryScreen.PatchAlbum(msg.ItemID, msg.Req.Name, msg.Req.Artists, msg.Req.ProductionYear) m.syncQueueScreen() + return m, tea.Batch(cmd, albumCmd) } return m, cmd @@ -553,13 +551,14 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { _ = m.mediaCache.Close() m.mediaCache = nil } + var errCmd tea.Cmd if m.cfg != nil { m.cfg.Server.Address = msg.ServerURL m.cfg.Server.Username = msg.Username m.cfg.Server.Token = msg.Token m.cfg.Server.UserID = msg.UserID if err := config.Save(filepath.Join(config.ConfigDir(), "config.toml"), *m.cfg); err != nil { - _ = m.err.SetError(fmt.Errorf("failed to save config: %w", err)) + errCmd = m.err.SetError(fmt.Errorf("failed to save config: %w", err)) } } deviceName, deviceID := "", "" @@ -571,7 +570,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.playlistsScreen.SetClient(m.client) var cmd tea.Cmd m.loginScreen, cmd = m.loginScreen.Update(msg) - return m, tea.Batch(cmd, m.fetchMusicLibrariesCmd()) + return m, tea.Batch(cmd, m.fetchMusicLibrariesCmd(), errCmd) case musicLibrariesLoadedMsg: if msg.err == nil && len(msg.libraries) > 0 { @@ -759,7 +758,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.navigate(ScreenMetadataEdit) case components.ErrorDismissMsg: - m.err.Dismiss() + m.err.HandleDismiss(msg) return m, nil case queue.JumpQueueMsg: @@ -840,17 +839,9 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, player.SetPauseCmd(m.mpv, !m.playerState.Playing) } case "next": - newM, cmd := m.startPlaybackAt(m.nextIndex(m.currentIndex + 1)) - return newM, cmd + return m.playNext() case "prev": - if m.playerState.Position > 3.0 { - if m.mpv != nil { - return m, player.SeekCmd(m.mpv, 0) - } - } else { - newM, cmd := m.startPlaybackAt(m.currentIndex - 1) - return newM, cmd - } + return m.playPrevious() case "shuffle": if len(m.tracks) > 1 { currentID := "" @@ -967,17 +958,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m.isSubliminalActive() { return m, nil } - if m.playerState.Position > 3.0 { - if m.mpv != nil { - return m, player.SeekCmd(m.mpv, 0) - } - } else { - newM, cmd := m.startPlaybackAt(m.currentIndex - 1) - return newM, cmd - } - - case mpris.SeekMsg: - return m.handleSeek(msg.Offset) + return m.playPrevious() case mpris.SeekRelativeMsg: return m.handleSeek(msg.OffsetSeconds) @@ -1023,6 +1004,20 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, cmd } +// isScreenKey reports whether the active screen binds msg itself. The screen +// then gets the key before the playback keys: S on the library and the +// playlists queues the selection shuffled, and r on the queue repeats the +// selected track. +func (m *Model) isScreenKey(msg tea.KeyMsg) bool { + switch m.screen { + case ScreenLibrary, ScreenPlaylists: + return msg.String() == "S" + case ScreenQueue: + return msg.String() == "r" + } + return false +} + // View is defined in render.go. // ModelAccessor implementation for mpris.Bridge.Bind diff --git a/internal/spruce/app/model_test.go b/internal/spruce/app/model_test.go index 3766b8b..084a01d 100644 --- a/internal/spruce/app/model_test.go +++ b/internal/spruce/app/model_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "path/filepath" + "slices" "strings" "testing" "time" @@ -17,9 +18,11 @@ import ( "github.com/Thelost77/pine/internal/spruce/jellyfin" "github.com/Thelost77/pine/internal/spruce/screens/library" "github.com/Thelost77/pine/internal/spruce/screens/login" + "github.com/Thelost77/pine/internal/spruce/screens/metadataedit" "github.com/Thelost77/pine/internal/spruce/screens/playlists" "github.com/Thelost77/pine/internal/spruce/screens/queue" "github.com/Thelost77/pine/internal/ui/components" + "github.com/charmbracelet/bubbles/list" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" ) @@ -488,8 +491,8 @@ func TestLibraryLoadUnauthorizedResetsPlaybackAndQueue(t *testing.T) { if m.IsPlaying() || len(m.tracks) != 0 || m.currentIndex != -1 { t.Fatalf("expected stopped empty playback state, playing=%v tracks=%d index=%d", m.IsPlaying(), len(m.tracks), m.currentIndex) } - if len(m.queueScreen.Tracks()) != 0 || m.mprisState.QueueLength() != 0 { - t.Fatalf("expected cleared queue projections, screen=%d mpris=%d", len(m.queueScreen.Tracks()), m.mprisState.QueueLength()) + if len(m.queueScreen.Tracks()) != 0 || m.mprisState.CanGoNext() { + t.Fatalf("expected cleared queue projections, screen=%d mpris next=%v", len(m.queueScreen.Tracks()), m.mprisState.CanGoNext()) } if m.repeatTrackID != "" || m.repeatQueue || m.playerState.RepeatStatus != "" { t.Fatalf("expected cleared repeat state, track=%q queue=%v status=%q", m.repeatTrackID, m.repeatQueue, m.playerState.RepeatStatus) @@ -727,9 +730,6 @@ func TestAppModel_MPRISCmdHelpers(t *testing.T) { if cmd := m.mprisTitleCmd(); cmd != nil { t.Errorf("expected nil cmd when bridge is nil, got %v", cmd) } - if cmd := m.mprisPositionCmd(); cmd != nil { - t.Errorf("expected nil cmd when bridge is nil, got %v", cmd) - } if cmd := m.mprisVolumeCmd(); cmd != nil { t.Errorf("expected nil cmd when bridge is nil, got %v", cmd) } @@ -742,7 +742,7 @@ func TestAppModel_MPRISCmdHelpers(t *testing.T) { func TestAppModel_SleepTimer(t *testing.T) { m := New(nil, nil) - m.screen = ScreenLibrary + m.screen = ScreenQueue tracks := []jellyfin.Track{{ID: "t-1", Name: "Track One"}} newM, _ := m.Update(library.PlayTracksMsg{Tracks: tracks, StartIndex: 0}) m = newM.(*Model) @@ -1085,3 +1085,267 @@ func TestAppModel_EmptyAndFailedQueueAddsDoNotConfirmSuccess(t *testing.T) { } }) } + +func TestScreenKeysWorkDuringPlayback(t *testing.T) { + m := New(nil, nil) + m.SetSize(80, 24) + m.tracks = []jellyfin.Track{{ID: "t-1", Name: "Track 1"}, {ID: "t-2", Name: "Track 2"}} + m.currentIndex = 0 + m.syncQueueScreen() + m.libraryScreen, _ = m.libraryScreen.Update(library.AlbumsLoadedMsg{ + Albums: []jellyfin.Album{{ID: "alb-1", Name: "Album One"}}, + }) + m.playlistsScreen, _ = m.playlistsScreen.Update(playlists.PlaylistsLoadedMsg{ + Playlists: []jellyfin.Playlist{{ID: "pl-1", Name: "Road Trip"}}, + }) + + for _, screen := range []Screen{ScreenLibrary, ScreenPlaylists} { + m.screen = screen + var cmd tea.Cmd + m, cmd = update(m, keyMsg("S")) + if m.sleepDuration != 0 { + t.Fatalf("S on screen %v set the sleep timer to %v", screen, m.sleepDuration) + } + if cmd == nil { + t.Fatalf("S on screen %v returned no command", screen) + } + if msg, ok := cmd().(library.AddShuffledTracksToQueueMsg); !ok { + t.Fatalf("S on screen %v returned %T, want AddShuffledTracksToQueueMsg", screen, msg) + } + } + + m.screen = ScreenQueue + m, _ = update(m, keySpecial(tea.KeyDown)) + m, cmd := update(m, keyMsg("r")) + m, _ = execCmd(m, cmd) + if m.repeatTrackID != "t-2" { + t.Fatalf("r on the selected queue row repeats %q, want t-2", m.repeatTrackID) + } +} + +func TestQueueRowsKeepTheirIndexesWithActiveFilter(t *testing.T) { + m := New(nil, nil) + m.SetSize(80, 24) + m.screen = ScreenQueue + m.tracks = []jellyfin.Track{ + {ID: "a-1", Name: "Alpha One"}, + {ID: "b", Name: "Bravo"}, + {ID: "a-2", Name: "Alpha Two"}, + } + m.currentIndex = 1 + m.syncQueueScreen() + + m = applyKeyWithFilter(m, keyMsg("/")) + m = applyKeyWithFilter(m, keyMsg("Alpha")) + m = applyKeyWithFilter(m, keySpecial(tea.KeyEnter)) + if !m.queueScreen.HasActiveFilter() { + t.Fatal("expected an active queue filter") + } + + for range 2 { + var cmd tea.Cmd + m, cmd = update(m, keyMsg("d")) + m, _ = execCmd(m, cmd) + } + if len(m.tracks) != 1 || m.tracks[0].ID != "b" || m.CurrentItemID() != "b" { + t.Fatalf("queue after removing both filtered rows = %+v, current %q; want only b", m.tracks, m.CurrentItemID()) + } +} + +func TestPositionTickKeepsTheSelectedRowOfAFilteredQueue(t *testing.T) { + m := New(nil, nil) + m.SetSize(80, 24) + m.screen = ScreenQueue + for i := range 60 { + m.tracks = append(m.tracks, jellyfin.Track{ID: fmt.Sprintf("a-%d", i), Name: fmt.Sprintf("Alpha %02d", i)}) + } + m.tracks = append(m.tracks, jellyfin.Track{ID: "b", Name: "Bravo"}) + m, _ = m.startPlaybackAt(60) + + m = applyKeyWithFilter(m, keyMsg("/")) + m = applyKeyWithFilter(m, keyMsg("Alpha")) + m = applyKeyWithFilter(m, keySpecial(tea.KeyEnter)) + // The filtered rows fill more than one page, so the selection leaves the + // first page. + for range 25 { + m, _ = update(m, keySpecial(tea.KeyDown)) + } + before := selectedQueueIndex(t, m) + + m, _ = update(m, player.PositionMsg{Generation: m.playGeneration, Position: 5, Duration: 100}) + if after := selectedQueueIndex(t, m); after != before { + t.Fatalf("selected queue index after a position tick = %d; want %d", after, before) + } +} + +// selectedQueueIndex returns the queue index that 'd' removes. +func selectedQueueIndex(t *testing.T, m *Model) int { + t.Helper() + _, cmd := m.queueScreen.Update(keyMsg("d")) + if cmd == nil { + t.Fatal("the queue has no selected row") + } + return cmd().(queue.RemoveQueueMsg).Index +} + +// applyKeyWithFilter sends key to m and feeds the filter results back. +func applyKeyWithFilter(m *Model, key tea.KeyMsg) *Model { + m, cmd := update(m, key) + return applyFilterMatches(m, cmd) +} + +func applyFilterMatches(m *Model, cmd tea.Cmd) *Model { + if cmd == nil { + return m + } + switch msg := cmd().(type) { + case tea.BatchMsg: + for _, batchCmd := range msg { + m = applyFilterMatches(m, batchCmd) + } + case list.FilterMatchesMsg: + m, _ = update(m, msg) + } + return m +} + +func TestLoginAfterAuthResetDropsTheLibraryOfTheOldSession(t *testing.T) { + m := New(nil, nil) + m.SetSize(80, 24) + m, _ = update(m, login.LoginSuccessMsg{Token: "tok-old", ServerURL: "http://old.invalid", Username: "old", UserID: "usr-old"}) + m.libraryScreen, _ = m.libraryScreen.Update(library.AlbumsLoadedMsg{ + Albums: []jellyfin.Album{{ID: "alb-old", Name: "Old Album"}}, + }) + m.playlistsScreen, _ = m.playlistsScreen.Update(playlists.PlaylistsLoadedMsg{ + Playlists: []jellyfin.Playlist{{ID: "pl-old", Name: "Old Playlist"}}, + }) + + m, _ = update(m, library.TracksLoadedMsg{Err: &jellyfin.HTTPStatusError{StatusCode: http.StatusUnauthorized}}) + if m.screen != ScreenLogin { + t.Fatalf("expected the login screen after 401, got %v", m.screen) + } + m, _ = update(m, login.LoginSuccessMsg{Token: "tok-new", ServerURL: "http://new.invalid", Username: "new", UserID: "usr-new"}) + + if albums := m.libraryScreen.Albums(); len(albums) != 0 { + t.Fatalf("albums of the old session remain after a new login: %+v", albums) + } + if lists := m.playlistsScreen.Playlists(); len(lists) != 0 { + t.Fatalf("playlists of the old session remain after a new login: %+v", lists) + } +} + +func TestPaletteQueueResultJumpsToTheQueuedTrack(t *testing.T) { + m := New(nil, nil) + m.SetSize(80, 24) + m.tracks = []jellyfin.Track{ + {ID: "t-1", Name: "Airbag"}, + {ID: "t-2", Name: "Lucky"}, + {ID: "t-3", Name: "Karma Police"}, + } + m.currentIndex = 0 + + var result *components.PaletteItem + for _, item := range m.contentSearchFunc()("Karma") { + if strings.HasPrefix(item.Label, "Queue: ") { + result = &item + } + } + if result == nil { + t.Fatal("expected a queue result for Karma") + } + newM, _ := m.handlePaletteAction(result.Action, result.ItemID, result.Data) + m = newM.(*Model) + if len(m.tracks) != 3 || m.currentIndex != 2 { + t.Fatalf("queue length = %d, current index = %d; want 3 tracks at index 2", len(m.tracks), m.currentIndex) + } +} + +func TestAlbumMetadataSaveUpdatesTheAlbumList(t *testing.T) { + m := New(nil, nil) + m.SetSize(80, 24) + m.libraryScreen, _ = m.libraryScreen.Update(library.AlbumsLoadedMsg{ + Albums: []jellyfin.Album{{ID: "alb-1", Name: "Old Name", Artists: []string{"Old Artist"}, ProductionYear: 1999}}, + }) + + year := 2001 + m, _ = update(m, metadataedit.SavedMsg{ItemID: "alb-1", Req: jellyfin.UpdateItemRequest{ + ID: "alb-1", + Name: "New Name", + Artists: []string{"New Artist"}, + ProductionYear: &year, + }}) + + albums := m.libraryScreen.Albums() + if len(albums) != 1 || albums[0].Name != "New Name" || !slices.Equal(albums[0].Artists, []string{"New Artist"}) || albums[0].ProductionYear != 2001 { + t.Fatalf("albums after save = %+v", albums) + } + if album, ok := m.libraryScreen.SelectedAlbum(); !ok || album.Name != "New Name" { + t.Fatalf("album row after save = %+v", album) + } +} + +func TestPreviousAtTheFirstTrackKeepsPlaying(t *testing.T) { + for name, msg := range map[string]tea.Msg{ + "key": keyMsg("p"), + "mpris": mpris.PreviousMsg{}, + "queue": queue.QueueActionMsg{Action: "prev"}, + "palette": nil, + } { + t.Run(name, func(t *testing.T) { + m := New(nil, nil) + m.screen = ScreenLibrary + m.tracks = []jellyfin.Track{{ID: "t-1", Name: "Track 1"}, {ID: "t-2", Name: "Track 2"}} + m.currentIndex = 0 + m.playerState.Position = 1 + if msg == nil { + newM, _ := m.handlePaletteAction(components.ActionPrevTrack, "", nil) + m = newM.(*Model) + } else { + m, _ = update(m, msg) + } + if !m.IsPlaying() || m.currentIndex != 0 { + t.Fatalf("previous at the first track: playing=%v index=%d, want index 0", m.IsPlaying(), m.currentIndex) + } + }) + } +} + +func TestNextAtTheLastTrack(t *testing.T) { + for name, msg := range map[string]tea.Msg{ + "key": keyMsg("n"), + "mpris": mpris.NextMsg{}, + "queue": queue.QueueActionMsg{Action: "next"}, + "palette": nil, + } { + for _, repeatQueue := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/repeat=%v", name, repeatQueue), func(t *testing.T) { + m := New(nil, nil) + m.screen = ScreenLibrary + m.tracks = []jellyfin.Track{{ID: "t-1", Name: "Track 1"}, {ID: "t-2", Name: "Track 2"}} + m.currentIndex = 1 + m.repeatQueue = repeatQueue + if msg == nil { + newM, _ := m.handlePaletteAction(components.ActionNextTrack, "", nil) + m = newM.(*Model) + } else { + m, _ = update(m, msg) + } + switch { + case repeatQueue: + if !m.IsPlaying() || m.currentIndex != 0 { + t.Fatalf("next with queue repeat: playing=%v index=%d, want index 0", m.IsPlaying(), m.currentIndex) + } + case name == "mpris": + // MPRIS Next stops the playback at the end of the tracklist. + if m.IsPlaying() { + t.Fatalf("MPRIS next at the last track: index=%d, want a stop", m.currentIndex) + } + default: + if !m.IsPlaying() || m.currentIndex != 1 { + t.Fatalf("next at the last track: playing=%v index=%d, want index 1", m.IsPlaying(), m.currentIndex) + } + } + }) + } + } +} diff --git a/internal/spruce/app/mpris_state.go b/internal/spruce/app/mpris_state.go index c421b34..189d380 100644 --- a/internal/spruce/app/mpris_state.go +++ b/internal/spruce/app/mpris_state.go @@ -19,7 +19,6 @@ type MprisState struct { minimumRate float64 maximumRate float64 volume int - queueLength int canSeek bool canGoNext bool canGoPrevious bool @@ -169,12 +168,3 @@ func (s *MprisState) CanGoPrevious() bool { defer s.mu.RUnlock() return s.canGoPrevious } - -func (s *MprisState) QueueLength() int { - if s == nil { - return 0 - } - s.mu.RLock() - defer s.mu.RUnlock() - return s.queueLength -} diff --git a/internal/spruce/app/palette.go b/internal/spruce/app/palette.go index 700bfcc..04de9e9 100644 --- a/internal/spruce/app/palette.go +++ b/internal/spruce/app/palette.go @@ -156,13 +156,13 @@ func (m *Model) contentSearchFunc() components.SearchFunc { texts = append(texts, label) } - for _, t := range m.tracks { + for i, t := range m.tracks { label := fmt.Sprintf("Queue: %s — %s", t.Name, t.DisplayArtist()) candidates = append(candidates, components.PaletteItem{ Label: label, Action: components.ActionPlayDirect, ItemID: t.ID, - Data: t, + Data: queue.JumpQueueMsg{Index: i}, }) texts = append(texts, label) } @@ -255,21 +255,9 @@ func (m *Model) handlePaletteAction(action components.PaletteAction, itemID stri } return m, nil case components.ActionNextTrack: - if len(m.tracks) > 0 && m.currentIndex+1 < len(m.tracks) { - return m.startPlaybackAt(m.nextIndex(m.currentIndex + 1)) - } - return m, nil + return m.playNext() case components.ActionPrevTrack: - if m.playerState.Position > 3.0 { - if m.mpv != nil { - return m, player.SeekCmd(m.mpv, 0) - } - return m, nil - } - if len(m.tracks) > 0 && m.currentIndex-1 >= 0 { - return m.startPlaybackAt(m.currentIndex - 1) - } - return m, nil + return m.playPrevious() case components.ActionClearQueue: return m.Update(queue.QueueActionMsg{Action: "clear"}) case components.ActionShuffleQueue: @@ -386,6 +374,9 @@ func (m *Model) handlePaletteAction(action components.PaletteAction, itemID stri if m.isSubliminalActive() { return m, m.err.SetError(fmt.Errorf("stop subliminal mode before starting another track")) } + if jump, ok := data.(queue.JumpQueueMsg); ok { + return m.startPlaybackAt(jump.Index) + } if track, ok := data.(jellyfin.Track); ok { m.tracks = append(m.tracks, track) return m.startPlaybackAt(len(m.tracks) - 1) diff --git a/internal/spruce/app/playback.go b/internal/spruce/app/playback.go index 221b05b..6487dd7 100644 --- a/internal/spruce/app/playback.go +++ b/internal/spruce/app/playback.go @@ -17,6 +17,8 @@ func (m *Model) startPlaybackAt(index int) (*Model, tea.Cmd) { return m.stopPlayback() } + restart := m.CurrentItemID() == m.tracks[index].ID + stopReqCmd := m.reportStoppedCmd() m.currentIndex = index m.pendingRepeatIndex = -1 m.pendingRepeatItemID = "" @@ -32,11 +34,16 @@ func (m *Model) startPlaybackAt(index int) (*Model, tea.Cmd) { logger.Info("starting track playback", "index", index, "id", track.ID, "title", track.Name) m.syncQueueScreen() + if restart { + // MPRIS clients see the same track, so they need the new position. + m.mprisSeeked(0) + } var cmds []tea.Cmd if m.client != nil { playSessionID := strconv.FormatInt(time.Now().UnixNano(), 16) m.playSessionID = playSessionID + m.playItemID = track.ID source := m.client.StreamURL(track.ID, playSessionID) streamHeaders := m.client.StreamHeaders() if m.mediaCache != nil { @@ -49,13 +56,18 @@ func (m *Model) startPlaybackAt(index int) (*Model, tea.Cmd) { itemID := track.ID startReqCmd := func() tea.Msg { + // The stop report of the previous track goes first, so that the + // server gets the reports in the order of the playback. + if stopReqCmd != nil { + stopReqCmd() + } _ = client.ReportPlaybackStart(context.Background(), itemID, playSessionID) return nil } cmds = append(cmds, startReqCmd) if m.mpv != nil { - cmds = append(cmds, player.LaunchCmd(m.mpv, source, 0, 0, false, streamHeaders, m.playerState.Volume, m.playGeneration)) + cmds = append(cmds, player.LaunchCmd(m.mpv, source, 0, false, streamHeaders, m.playerState.Volume, m.playGeneration)) } } if m.repeatQueue { @@ -69,7 +81,7 @@ func (m *Model) startPlaybackAt(index int) (*Model, tea.Cmd) { func (m *Model) stopPlayback() (*Model, tea.Cmd) { logger.Info("stopping playback") - position := m.playerState.Position + cmds := []tea.Cmd{m.reportStoppedCmd()} m.playGeneration++ m.playerState.Title = "" m.playerState.Playing = false @@ -80,18 +92,6 @@ func (m *Model) stopPlayback() (*Model, tea.Cmd) { m.sleepDuration = 0 m.playerState.SleepRemaining = "" - var cmds []tea.Cmd - if m.client != nil && m.currentIndex >= 0 && m.currentIndex < len(m.tracks) { - client := m.client - itemID := m.tracks[m.currentIndex].ID - playSessionID := m.playSessionID - stopReqCmd := func() tea.Msg { - _ = client.ReportPlaybackStopped(context.Background(), itemID, position, playSessionID) - return nil - } - cmds = append(cmds, stopReqCmd) - } - if m.mpv != nil { cmds = append(cmds, player.QuitCmd(m.mpv)) } @@ -101,6 +101,43 @@ func (m *Model) stopPlayback() (*Model, tea.Cmd) { return m, tea.Batch(cmds...) } +// reportStoppedCmd closes the Jellyfin play session of the track that plays. +// It returns nil if no play session is open. The report does not depend on +// the queue, because a queue change can remove the track before the stop. +func (m *Model) reportStoppedCmd() tea.Cmd { + itemID := m.playItemID + m.playItemID = "" + if m.client == nil || itemID == "" { + return nil + } + client := m.client + position := m.playerState.Position + playSessionID := m.playSessionID + return func() tea.Msg { + _ = client.ReportPlaybackStopped(context.Background(), itemID, position, playSessionID) + return nil + } +} + +// playNext plays the next track. At the end of the queue it does nothing, +// unless the queue repeats. +func (m *Model) playNext() (*Model, tea.Cmd) { + next := m.nextIndex(m.currentIndex + 1) + if next >= len(m.tracks) { + return m, nil + } + return m.startPlaybackAt(next) +} + +// playPrevious plays the previous track in the first 3 seconds of a track. +// Later, and at the first track, it plays the track again from the start. +func (m *Model) playPrevious() (*Model, tea.Cmd) { + if m.playerState.Position > 3.0 || m.currentIndex <= 0 { + return m.handleSeekAbsolute(0) + } + return m.startPlaybackAt(m.currentIndex - 1) +} + func (m *Model) setPlaybackPaused(paused bool) (*Model, tea.Cmd) { if !m.IsPlaying() { return m, nil @@ -195,20 +232,17 @@ func authorsEqual(a, b []string) bool { } type mprisStateSnapshot struct { - playing bool - paused bool - title string - authors []string - itemID string - position float64 - speed float64 - volume int + playing bool + paused bool + title string + authors []string + itemID string + speed float64 + volume int } func (m *Model) syncQueueScreen() { - if !m.queueScreen.IsFiltering() && !m.queueScreen.HasActiveFilter() { - m.queueScreen.SetQueue(m.tracks, m.currentIndex) - } + m.queueScreen.SetQueue(m.tracks, m.currentIndex) m.queueScreen.SetPlaybackState( m.IsPlaying(), m.IsPaused(), @@ -225,14 +259,13 @@ func (m *Model) syncQueueScreen() { var oldState, newState mprisStateSnapshot m.mprisState.Update(func(s *MprisState) { oldState = mprisStateSnapshot{ - playing: s.playing, - paused: s.paused, - title: s.title, - authors: s.authors, - itemID: s.itemID, - position: s.position, - speed: s.speed, - volume: s.volume, + playing: s.playing, + paused: s.paused, + title: s.title, + authors: s.authors, + itemID: s.itemID, + speed: s.speed, + volume: s.volume, } normalActive := m.IsPlaying() subliminalActive := m.isSubliminalRunning() @@ -274,16 +307,14 @@ func (m *Model) syncQueueScreen() { s.maximumRate = 4.0 } s.volume = m.playerState.Volume - s.queueLength = len(m.tracks) newState = mprisStateSnapshot{ - playing: s.playing, - paused: s.paused, - title: s.title, - authors: s.authors, - itemID: s.itemID, - position: s.position, - speed: s.speed, - volume: s.volume, + playing: s.playing, + paused: s.paused, + title: s.title, + authors: s.authors, + itemID: s.itemID, + speed: s.speed, + volume: s.volume, } }) @@ -297,7 +328,6 @@ func (m *Model) syncQueueScreen() { oldState.itemID != newState.itemID || !authorsEqual(oldState.authors, newState.authors) volumeChanged := oldState.volume != newState.volume - positionChanged := oldState.position != newState.position if playbackChanged { server.PlaybackChanged() @@ -308,13 +338,6 @@ func (m *Model) syncQueueScreen() { if volumeChanged { server.VolumeChanged() } - if positionChanged { - now := time.Now() - if now.Sub(m.lastMprisEmit) >= time.Second { - m.lastMprisEmit = now - server.Seeked(newState.position) - } - } } } } @@ -322,19 +345,7 @@ func (m *Model) syncQueueScreen() { } func (m *Model) handleSeek(offset float64) (*Model, tea.Cmd) { - if m.mpv == nil || !m.IsPlaying() { - return m, nil - } - target := m.playerState.Position + offset - if target < 0 { - target = 0 - } - if m.playerState.Duration > 0 && target > m.playerState.Duration { - target = m.playerState.Duration - } - m.playerState.Position = target - m.syncQueueScreen() - return m, player.SeekCmd(m.mpv, target) + return m.handleSeekAbsolute(m.playerState.Position + offset) } func (m *Model) handleSeekAbsolute(pos float64) (*Model, tea.Cmd) { @@ -349,9 +360,21 @@ func (m *Model) handleSeekAbsolute(pos float64) (*Model, tea.Cmd) { } m.playerState.Position = pos m.syncQueueScreen() + m.mprisSeeked(pos) return m, player.SeekCmd(m.mpv, pos) } +// mprisSeeked tells MPRIS clients about a position change that the rate does +// not explain. +func (m *Model) mprisSeeked(position float64) { + if m.mprisBridge == nil { + return + } + if server := m.mprisBridge.Server(); server != nil { + server.Seeked(position) + } +} + func (m *Model) mprisPlaybackCmd() tea.Cmd { if m.mprisBridge == nil { return nil @@ -408,26 +431,6 @@ func (m *Model) mprisTitleCmd() tea.Cmd { } } -func (m *Model) mprisPositionCmd() tea.Cmd { - if m.mprisBridge == nil { - return nil - } - now := time.Now() - if now.Sub(m.lastMprisEmit) < time.Second { - return nil - } - m.lastMprisEmit = now - server := m.mprisBridge.Server() - if server == nil { - return nil - } - pos := m.playerState.Position - return func() tea.Msg { - server.Seeked(pos) - return nil - } -} - func (m *Model) mprisVolumeCmd() tea.Cmd { if m.mprisBridge == nil { return nil diff --git a/internal/spruce/config/config_test.go b/internal/spruce/config/config_test.go index 2ee121c..bf3aa29 100644 --- a/internal/spruce/config/config_test.go +++ b/internal/spruce/config/config_test.go @@ -48,9 +48,6 @@ func TestLoadEmptyPathReturnsDefaults(t *testing.T) { if cfg.Theme.Border != "#4f585e" { t.Errorf("expected border #4f585e, got %q", cfg.Theme.Border) } - if cfg.Theme.Warning != "#dbbc7f" { - t.Errorf("expected warning #dbbc7f, got %q", cfg.Theme.Warning) - } if cfg.Theme.Info != "#7fbbb3" { t.Errorf("expected info #7fbbb3, got %q", cfg.Theme.Info) } diff --git a/internal/spruce/jellyfin/client.go b/internal/spruce/jellyfin/client.go index 9f59997..f9d7f12 100644 --- a/internal/spruce/jellyfin/client.go +++ b/internal/spruce/jellyfin/client.go @@ -555,7 +555,13 @@ func (c *Client) UpdateItem(ctx context.Context, itemID string, req UpdateItemRe itemData["Album"] = req.Album } if req.Artists != nil { - itemData["Artists"] = req.Artists + // Jellyfin sets the artists of an item from the names in ArtistItems. + // It ignores Artists. + artistItems := make([]map[string]string, len(req.Artists)) + for i, name := range req.Artists { + artistItems[i] = map[string]string{"Name": name} + } + itemData["ArtistItems"] = artistItems } if req.IndexNumber != nil { itemData["IndexNumber"] = *req.IndexNumber diff --git a/internal/spruce/jellyfin/client_test.go b/internal/spruce/jellyfin/client_test.go index 3285d3a..8f8f099 100644 --- a/internal/spruce/jellyfin/client_test.go +++ b/internal/spruce/jellyfin/client_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "reflect" "strings" "testing" @@ -340,3 +341,33 @@ func TestClient_StreamHelpersAndProgress(t *testing.T) { t.Error("progress endpoint was not called") } } + +func TestClient_UpdateItemSendsArtistItems(t *testing.T) { + var posted map[string]any + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && r.URL.Path == "/Users/user-123/Items/trk-1": + _, _ = w.Write([]byte(`{"Id":"trk-1","Name":"Old","Artists":["Old Artist"],"ArtistItems":[{"Name":"Old Artist","Id":"art-1"}]}`)) + case r.Method == http.MethodPost && r.URL.Path == "/Items/trk-1": + if err := json.NewDecoder(r.Body).Decode(&posted); err != nil { + t.Errorf("decode update body: %v", err) + } + w.WriteHeader(http.StatusNoContent) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + } + })) + defer server.Close() + + client := NewClient(server.URL, "token-xyz", "user-123", "Test device", "test-device") + err := client.UpdateItem(context.Background(), "trk-1", UpdateItemRequest{ID: "trk-1", Artists: []string{"New A", "New B"}}) + if err != nil { + t.Fatalf("UpdateItem error: %v", err) + } + // Jellyfin sets the artists of an item from ArtistItems, not from Artists. + want := []any{map[string]any{"Name": "New A"}, map[string]any{"Name": "New B"}} + if !reflect.DeepEqual(posted["ArtistItems"], want) { + t.Fatalf("ArtistItems = %#v, want %#v", posted["ArtistItems"], want) + } +} diff --git a/internal/spruce/screens/library/model.go b/internal/spruce/screens/library/model.go index a91edaf..8802a87 100644 --- a/internal/spruce/screens/library/model.go +++ b/internal/spruce/screens/library/model.go @@ -288,6 +288,35 @@ func (m *Model) PatchTrack(id, name string, artists []string, album string) { } } +// PatchAlbum updates a single album in the album list without any network call. +func (m *Model) PatchAlbum(id, name string, artists []string, year *int) tea.Cmd { + patch := func(a *jellyfin.Album) { + if name != "" { + a.Name = name + } + if artists != nil { + a.Artists = artists + } + if year != nil { + a.ProductionYear = *year + } + } + if m.selectedAlbum.ID == id { + patch(&m.selectedAlbum) + } + for i := range m.albums { + if m.albums[i].ID == id { + selectedID := "" + if selected, ok := m.albumList.SelectedItem().(albumItem); ok { + selectedID = selected.Album.ID + } + patch(&m.albums[i]) + return libraryRefilterCmd(m.rebuildAlbumList(selectedID)) + } + } + return nil +} + func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { switch msg := msg.(type) { case components.ItemFlashExpiredMsg: diff --git a/internal/spruce/screens/playlists/messages.go b/internal/spruce/screens/playlists/messages.go index eeb0143..d19d451 100644 --- a/internal/spruce/screens/playlists/messages.go +++ b/internal/spruce/screens/playlists/messages.go @@ -11,8 +11,9 @@ type PlaylistsLoadedMsg struct { } type PlaylistTracksLoadedMsg struct { - Tracks []jellyfin.Track - Err error + PlaylistID string + Tracks []jellyfin.Track + Err error } // RefilterMsg routes an asynchronous list refilter back to the playlists model. diff --git a/internal/spruce/screens/playlists/model.go b/internal/spruce/screens/playlists/model.go index f817697..3dcb001 100644 --- a/internal/spruce/screens/playlists/model.go +++ b/internal/spruce/screens/playlists/model.go @@ -117,7 +117,7 @@ func (m Model) fetchPlaylistTracksCmd(playlistID string) tea.Cmd { return func() tea.Msg { logger.Info("fetching playlist tracks", "playlistID", playlistID) tracks, err := client.GetPlaylistTracks(context.Background(), playlistID) - return PlaylistTracksLoadedMsg{Tracks: tracks, Err: err} + return PlaylistTracksLoadedMsg{PlaylistID: playlistID, Tracks: tracks, Err: err} } } @@ -184,6 +184,10 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { return m, nil case PlaylistTracksLoadedMsg: + // Ignore a late reply for a playlist that is not open. + if msg.PlaylistID != "" && (msg.PlaylistID != m.selectedPlaylist.ID || m.level != LevelTracks) { + return m, nil + } m.loading = false m.err = msg.Err if msg.Err == nil { diff --git a/internal/spruce/screens/playlists/model_test.go b/internal/spruce/screens/playlists/model_test.go index a0bfdcb..7b9812d 100644 --- a/internal/spruce/screens/playlists/model_test.go +++ b/internal/spruce/screens/playlists/model_test.go @@ -171,6 +171,25 @@ func TestPlaylistsModel_TrackFavoritePreservesActiveFilter(t *testing.T) { } } +func TestPlaylistsModel_IgnoresTracksOfAPlaylistThatIsNotOpen(t *testing.T) { + m := New(ui.DefaultStyles()) + m.SetSize(80, 24) + + _ = m.SelectPlaylist(jellyfin.Playlist{ID: "pl-a", Name: "A"}) + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEscape}) + m, _ = m.Update(PlaylistTracksLoadedMsg{PlaylistID: "pl-a", Tracks: []jellyfin.Track{{ID: "a-1", Name: "Alpha"}}}) + if m.CurrentLevel() != LevelPlaylists { + t.Fatalf("a late reply for a closed playlist opened level %v", m.CurrentLevel()) + } + + _ = m.SelectPlaylist(jellyfin.Playlist{ID: "pl-b", Name: "B"}) + m, _ = m.Update(PlaylistTracksLoadedMsg{PlaylistID: "pl-b", Tracks: []jellyfin.Track{{ID: "b-1", Name: "Bravo"}}}) + m, _ = m.Update(PlaylistTracksLoadedMsg{PlaylistID: "pl-a", Tracks: []jellyfin.Track{{ID: "a-1", Name: "Alpha"}}}) + if got := playlistTrackNames(m.Tracks()); !slices.Equal(got, []string{"Bravo"}) { + t.Fatalf("tracks of playlist B = %v, want [Bravo]", got) + } +} + func applyPlaylistKey(m Model, key tea.KeyMsg) Model { var cmd tea.Cmd m, cmd = m.Update(key) diff --git a/internal/spruce/screens/queue/model.go b/internal/spruce/screens/queue/model.go index ee41ea0..610894d 100644 --- a/internal/spruce/screens/queue/model.go +++ b/internal/spruce/screens/queue/model.go @@ -108,8 +108,15 @@ func (m *Model) SetQueue(tracks []jellyfin.Track, currentIndex int) { IsCurrent: i == currentIndex, } } - cmd := m.list.SetItems(items) - _ = cmd // SetItems returns cmd for spinner/etc if needed + selected := m.list.Index() + if cmd := m.list.SetItems(items); cmd != nil { + // With a filter, SetItems matches the new items in a command. Apply the + // matches now, so that each visible row has its index in the queue. + // SetItems moves the selection to the first page before the matches + // arrive, so select the same row again. + m.list, _ = m.list.Update(cmd()) + m.list.Select(max(0, min(selected, len(m.list.VisibleItems())-1))) + } if !m.HasActiveFilter() && shouldSelectCurrent(oldTracks, tracks, oldCurrentIndex, currentIndex) { if currentIndex >= 0 && currentIndex < len(items) { m.list.Select(currentIndex) diff --git a/internal/ui/components/error.go b/internal/ui/components/error.go index 2102712..86cac4f 100644 --- a/internal/ui/components/error.go +++ b/internal/ui/components/error.go @@ -18,14 +18,20 @@ type ErrMsg struct { Err error } -// ErrorDismissMsg signals that the error banner should be dismissed. -type ErrorDismissMsg struct{} +// ErrorDismissMsg signals that the auto-dismiss time of an error ended. +// Generation identifies that error in the banner. +type ErrorDismissMsg struct { + Generation uint64 +} // ErrorBanner holds the state for the error banner overlay. type ErrorBanner struct { err error style lipgloss.Style width int + // generation counts the calls of SetError. It ties a dismiss tick to its + // error. + generation uint64 } // NewErrorBanner creates a new error banner with the given error style. @@ -43,7 +49,8 @@ func (b *ErrorBanner) SetWidth(w int) { // SetError sets the current error and returns a command to auto-dismiss. func (b *ErrorBanner) SetError(err error) tea.Cmd { b.err = err - return scheduleDismiss() + b.generation++ + return scheduleDismiss(b.generation) } // Dismiss clears the error. @@ -51,6 +58,14 @@ func (b *ErrorBanner) Dismiss() { b.err = nil } +// HandleDismiss clears the error if msg is the dismiss tick of the current +// error. The tick of an earlier error does nothing. +func (b *ErrorBanner) HandleDismiss(msg ErrorDismissMsg) { + if msg.Generation == b.generation { + b.err = nil + } +} + // HasError returns true if there is an active error. func (b ErrorBanner) HasError() bool { return b.err != nil @@ -96,9 +111,10 @@ func sanitizeTerminalText(msg string) string { }, msg) } -// scheduleDismiss returns a command that sends ErrorDismissMsg after the timeout. -func scheduleDismiss() tea.Cmd { +// scheduleDismiss returns a command that sends ErrorDismissMsg for the error +// of the generation after the timeout. +func scheduleDismiss(generation uint64) tea.Cmd { return tea.Tick(ErrorDismissTimeout, func(_ time.Time) tea.Msg { - return ErrorDismissMsg{} + return ErrorDismissMsg{Generation: generation} }) } diff --git a/internal/ui/components/error_test.go b/internal/ui/components/error_test.go index 4ec1ca5..fa76185 100644 --- a/internal/ui/components/error_test.go +++ b/internal/ui/components/error_test.go @@ -80,6 +80,22 @@ func TestDismiss(t *testing.T) { } } +func TestHandleDismissIgnoresTheTickOfAnEarlierError(t *testing.T) { + b := NewErrorBanner(defaultTestStyle()) + b.SetError(errors.New("first")) + firstTick := ErrorDismissMsg{Generation: b.generation} + b.SetError(errors.New("second")) + + b.HandleDismiss(firstTick) + if !b.HasError() { + t.Fatal("the tick of the first error dismissed the second error") + } + b.HandleDismiss(ErrorDismissMsg{Generation: b.generation}) + if b.HasError() { + t.Error("the tick of the second error did not dismiss it") + } +} + func TestSetErrorNil(t *testing.T) { b := NewErrorBanner(defaultTestStyle()) b.SetError(nil) diff --git a/internal/ui/components/palette.go b/internal/ui/components/palette.go index a96f54b..88ba403 100644 --- a/internal/ui/components/palette.go +++ b/internal/ui/components/palette.go @@ -76,12 +76,17 @@ type PaletteItem struct { LibraryID string ItemID string Data any + // PlayAction is the action of the key p. With ActionNone, p is a letter + // of the search. + PlayAction PaletteAction } func (i PaletteItem) Title() string { return i.Label } func (i PaletteItem) Description() string { return "" } func (i PaletteItem) FilterValue() string { return i.Label } +// SearchFunc gives the items for a query. The palette calls it in Update at +// each keystroke, so it must not block. type SearchFunc func(query string) []PaletteItem type Palette struct { @@ -178,7 +183,7 @@ func NewPalette() Palette { func (p *Palette) SetStyles(styles ui.Styles) { p.styles = styles p.delegate.styles = styles - p.delegate.delegate.Styles.SelectedTitle = styles.Selected.Foreground(lipgloss.Color("#d3c6aa")).Bold(true).Padding(0, 0) + p.delegate.delegate.Styles.SelectedTitle = styles.Selected.Bold(true).Padding(0, 0) p.delegate.delegate.Styles.NormalTitle = styles.Muted.Padding(0, 0) p.list.SetDelegate(p.delegate) @@ -208,6 +213,15 @@ func (p *Palette) Close() { p.visible = false } +// Refresh applies the query again, for results that the search function did +// not have at the last change of the query. With no query, it does nothing. +func (p *Palette) Refresh() { + if !p.visible || strings.TrimSpace(p.input.Value()) == "" { + return + } + p.applyFilter(p.input.Value()) +} + func (p *Palette) Visible() bool { return p.visible } @@ -268,12 +282,6 @@ func (p *Palette) Update(msg tea.Msg) (tea.Cmd, bool) { } func (p *Palette) updateSearchInput(msg tea.KeyMsg) (tea.Cmd, bool) { - if msg.Type == tea.KeyEsc { - p.focusSearch = false - p.input.Blur() - return nil, true - } - if msg.Type == tea.KeyEnter || msg.Type == tea.KeyTab { p.focusSearch = false p.input.Blur() @@ -341,16 +349,13 @@ func (p *Palette) updateList(msg tea.KeyMsg) (tea.Cmd, bool) { return nil, true } - if msg.String() == "p" { - if sel, ok := p.list.SelectedItem().(PaletteItem); ok && !sel.IsHeader && sel.Action == ActionContentNavigate { - p.lastAction = ActionPlayDirect - p.lastPayload = sel.Payload - p.lastLibraryID = sel.LibraryID - p.lastItemID = sel.ItemID - p.lastData = sel.Data - p.Close() - return nil, true - } + if sel, ok := p.playItem(); ok && msg.String() == "p" { + p.lastAction = sel.PlayAction + p.lastPayload = sel.Payload + p.lastLibraryID = sel.LibraryID + p.lastItemID = sel.ItemID + p.lastData = sel.Data + p.Close() return nil, true } @@ -384,9 +389,20 @@ func (p *Palette) updateList(msg tea.KeyMsg) (tea.Cmd, bool) { p.list.Select(0) } } + // The keys of the list, such as home and the page keys, do not skip + // headers. + if sel, ok := p.list.SelectedItem().(PaletteItem); ok && sel.IsHeader { + p.moveListSelection(1) + } return cmd, true } +// playItem returns the selected item if the key p plays it. +func (p *Palette) playItem() (PaletteItem, bool) { + sel, ok := p.list.SelectedItem().(PaletteItem) + return sel, ok && !sel.IsHeader && sel.PlayAction != ActionNone +} + func (p *Palette) moveListSelection(delta int) { items := p.list.Items() if len(items) == 0 { @@ -483,7 +499,11 @@ func (p Palette) View() string { if p.focusSearch { footer = p.styles.Muted.Render("type to filter esc/enter → results esc esc close") } else { - footer = p.styles.Muted.Render("↑↓/jk navigate enter open p play tab → search esc close") + play := "" + if _, ok := p.playItem(); ok { + play = "p play " + } + footer = p.styles.Muted.Render("↑↓/jk navigate enter open " + play + "tab → search esc close") } box := lipgloss.JoinVertical(lipgloss.Left, title, searchLine, listContent, footer) diff --git a/internal/ui/components/palette_test.go b/internal/ui/components/palette_test.go index 54501cf..38f206f 100644 --- a/internal/ui/components/palette_test.go +++ b/internal/ui/components/palette_test.go @@ -287,7 +287,7 @@ func TestPalettePlayDirect(t *testing.T) { p := NewPalette() p.Open([]PaletteItem{ {Label: "Go Home", Action: ActionGoHome}, - {Label: "Dune", Action: ActionContentNavigate, ItemID: "dune-1"}, + {Label: "Dune", Action: ActionContentNavigate, PlayAction: ActionPlayDirect, ItemID: "dune-1"}, }, nil) p.list.Select(1) @@ -302,15 +302,22 @@ func TestPalettePlayDirect(t *testing.T) { } } -func TestPalettePlayDirectOnNonContentDoesNothing(t *testing.T) { +// TestPalettePWithoutAPlayActionStartsASearch verifies that p is a search +// letter when the selected item has nothing to play. +func TestPalettePWithoutAPlayActionStartsASearch(t *testing.T) { p := NewPalette() p.Open([]PaletteItem{ {Label: "Go Home", Action: ActionGoHome}, }, nil) - _, _ = p.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'p'}}) + for _, r := range "pause" { + _, _ = p.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}}) + } if !p.Visible() { - t.Fatal("palette should stay open when 'p' on non-content item") + t.Fatal("palette should stay open when 'p' is typed") + } + if got := p.input.Value(); got != "pause" { + t.Errorf("search input = %q, want %q", got, "pause") } action, _, _, _, _ := p.SelectedAction() if action != ActionNone { @@ -318,6 +325,62 @@ func TestPalettePlayDirectOnNonContentDoesNothing(t *testing.T) { } } +// TestPaletteFooterShowsPlayOnlyForAnItemWithAPlayAction verifies that the +// footer offers p only when p plays the selected item. +func TestPaletteFooterShowsPlayOnlyForAnItemWithAPlayAction(t *testing.T) { + p := NewPalette() + p.SetStyles(ui.DefaultStyles()) + p.SetSize(80, 40) + p.Open([]PaletteItem{ + {Label: "Song", Action: ActionOpenSelected}, + }, nil) + + if view := p.View(); strings.Contains(view, "p play") { + t.Errorf("footer offers p play for an item without a play action: %q", view) + } + + p.Open([]PaletteItem{ + {Label: "Dune", Action: ActionContentNavigate, PlayAction: ActionPlayDirect}, + }, nil) + if view := p.View(); !strings.Contains(view, "p play") { + t.Errorf("footer does not offer p play for an item with a play action: %q", view) + } +} + +// TestPaletteListKeysDoNotSelectAHeader verifies that the keys that the list +// handles, such as home, select an action row and not a header. +func TestPaletteListKeysDoNotSelectAHeader(t *testing.T) { + p := NewPalette() + p.Open([]PaletteItem{ + {Label: "Navigation", IsHeader: true}, + {Label: "Go Home", Action: ActionGoHome}, + {Label: "Go Library", Action: ActionGoLibrary}, + }, nil) + + _, _ = p.Update(tea.KeyMsg{Type: tea.KeyDown}) + _, _ = p.Update(tea.KeyMsg{Type: tea.KeyHome}) + if got := p.list.Index(); got != 1 { + t.Fatalf("index after home = %d, want 1 (the first action row)", got) + } + _, _ = p.Update(tea.KeyMsg{Type: tea.KeyEnter}) + if action, _, _, _, _ := p.SelectedAction(); action != ActionGoHome { + t.Errorf("action after home and enter = %v, want ActionGoHome", action) + } +} + +// TestPaletteSelectedRowUsesTheThemeForeground verifies that the selected row +// has the foreground color of the theme. +func TestPaletteSelectedRowUsesTheThemeForeground(t *testing.T) { + theme := ui.DefaultTheme() + theme.Foreground = "#333333" + p := NewPalette() + p.SetStyles(ui.NewStyles(theme)) + + if got := p.delegate.delegate.Styles.SelectedTitle.GetForeground(); got != lipgloss.Color("#333333") { + t.Errorf("selected row foreground = %v, want #333333", got) + } +} + func TestMatchQuery(t *testing.T) { tests := []struct { label string diff --git a/internal/ui/styles.go b/internal/ui/styles.go index eb9f41f..d306813 100644 --- a/internal/ui/styles.go +++ b/internal/ui/styles.go @@ -11,7 +11,6 @@ type ThemeConfig struct { Muted string `toml:"muted"` Selected string `toml:"selected"` Border string `toml:"border"` - Warning string `toml:"warning"` Info string `toml:"info"` } @@ -25,7 +24,6 @@ func DefaultTheme() ThemeConfig { Muted: "#859289", Selected: "#475258", Border: "#4f585e", - Warning: "#dbbc7f", Info: "#7fbbb3", } }