diff --git a/AGENTS.md b/AGENTS.md index b0668ca..b6f064d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,7 +56,7 @@ The Architecture Map below describes pine and the shared packages. | `model.go` | Root Model struct, Update dispatcher, sleep timer, chapter overlay, command palette, 401 handling | | `playback.go` | Playback lifecycle: handlePlayCmd → handlePlaySessionMsg → handlePlayerReady → handlePositionMsg → handleSyncTick → stopPlayback → Cleanup. Track rollover for multi-track books. Session restore on startup. | | `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 | +| `render.go` | View composition: header + error banner + screen + hints + player footer + chapter overlay modal + confirmation overlay + scan box (`overlayScanBox`, at the right edge below the header and the error banner) | | `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, search snapshot prewarm, detail refresh | | `messages.go` | Screen enum, PlaySessionMsg, PlaySessionData, QueueEntry, all root-level message types | @@ -86,18 +86,18 @@ The Architecture Map below describes pine and the shared packages. | `library` | model.go, view.go | Paginated item list (50/page), infinite scroll prefetch at 80%, per-library page cache shared with search cache. Library switching with tab. | | `detail` | model.go, view.go | Viewport-scrollable content: description, series row, episodes list (podcasts), bookmarks list, inline bookmark editing, item deletion. Tab cycles focus between sections. | | `metadataedit` | model.go, view.go | Inline metadata editor for books and podcast episodes. | -| `serieslist` | model.go | Paginated series browser (50/page), infinite scroll. | +| `serieslist` | model.go | Paginated series browser (50/page), infinite scroll. The server sorts the series by name. Each row shows the number of books. | | `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` 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. | +| `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 of each library (`prewarmCacheCmd`). `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`. The palette searches the library of the current screen first, then each other library below a header with its name (`contentSearchFunc`). While the snapshot of a library is not ready, the last row is the header `Building index…`. When the palette opens, `openGlobalPalette` returns `PrebuildCmd` for each library with no ready snapshot. On each `CacheReadyMsg`, `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. 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. | +| `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. | +| `store.go` | SQLite-backed cache persistence and `ClearAll`. Each key in the database has the prefix `keyVersion` (`v2-`). Raise it when the type of a cached value changes. | ### MPRIS (internal/mpris/, shared) @@ -116,7 +116,7 @@ The server is written from the MPRIS 2.2 specification. The Go MPRIS server libr |------|---------------| | `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), ScanLibrary (`POST /api/libraries/{id}/scan`). The server answers the scan request before the scan, so ScanLibrary reads `lastScan` of `GET /api/libraries/{id}` until it changes. The cache client clears the cache after the scan, and `LibraryScannedMsg` loads the home screen and the library screen again. | +| `libraries.go` | GetLibraries, GetPersonalized, GetLibraryItems (paginated), GetLibraryItemsBatch (10 concurrent), GetLibrarySeries, GetSeriesContents, FilterAudioLibraries (keeps a book library when its longest item, `sort=media.duration` and `desc=1`, has audio, or when it has no items), ScanLibrary (`POST /api/libraries/{id}/scan`). The server answers the scan request before the scan, so ScanLibrary reads `lastScan` of `GET /api/libraries/{id}` until it changes. The cache client clears the cache after the scan. `LibraryScannedMsg` then loads the home screen and the library screen again, and the open series list, series screen, and detail screen of that library (`reloadOpenScreensCmd`). | | `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), 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}]`) | @@ -147,6 +147,10 @@ Styles from theme config. Format helpers (timestamps, durations). `RunProgram` r - 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. - `ctrl+p` opens the global command palette from each screen, but not while a text input or a dialog gets the keys - The palette shows `Browse Series` in its Navigation group on each screen whose library is a book library, but not on the series list. `buildStaticPaletteItems` adds the entry for the library that `currentLibraryForSearch` returns, which is also the library that the palette searches. Do not add a `Browse Series` entry to the palette actions of a screen. +- The palette entries `Go Library` and `Scan Library` use the library of the current screen (`currentLibraryForSearch`). The sessions screen of an item uses the library of that item (`sessions.Target.LibraryID`). The sessions of all items use the library of the home screen. While a scan runs, `scanStatus` holds the text of the scan box, and `Scan Library` does nothing. +- `Refresh` clears the cache in a command (`cache.Client.Invalidate`). `CacheClearedMsg` then loads the library list and the home screen (`home.RefreshCmd`), the library screen, and the open series list, series screen, and detail screen again. The library list stays on the home model until the answer comes, and the answer selects the same library by its ID. +- A `home.PersonalizedMsg` has the generation of its load (`loadingGen`). The home screen drops the answer of an earlier load. +- `serieslist.LoadedMsg` and `series.LoadedMsg` go to their own screen model, also when that screen is behind the active screen, because a scan and `Refresh` load the screens of the back stack again. `serieslist.LoadedMsg` has the library ID and the generation of its load, and `series.LoadedMsg` has the series ID. A screen drops a message that does not match. A reload of the series list uses `ReloadCmd`, which raises the generation and blocks the load of a next page. - A text input or a confirmation dialog of a screen gets each key, except ctrl+c. `capturesKeys` in `playback.go` is true for the login screen, the metadata editor, a list filter, and the bookmark title editor. It is also true for the confirmation dialog of the detail screen. `Update` in `model.go` then gives the key to the screen, before the global keys, the chapter overlay, the error banner, and the playback keys. The help overlay and the command palette get the keys first while they are open. If you add a text input or a dialog to a screen, add it to `capturesKeys`. - Duration from ABS takes precedence over mpv-reported duration (streaming content reports 0) - Each launch makes a new mpv handle, which plays at the speed 1.0. `handlePlayerReady` sets the speed of the model in the new player. diff --git a/README.md b/README.md index b995a25..baf2e01 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ The remaining sections describe pine. For spruce, see [docs/spruce/README.md](do - Multiple library support with tab switching - Delete books and podcast episodes from the server - Scan a library on the server from the command palette (admin users only), then reload the lists when the scan ends +- Refresh from the command palette: clear the local cache, then load the screens and the library list again - Keyboard-driven navigation - Configurable colors and keys, with the Everforest dark theme as the default - Session restore — pick up where you left off diff --git a/internal/abs/filter_test.go b/internal/abs/filter_test.go index 7fbe551..2d4155c 100644 --- a/internal/abs/filter_test.go +++ b/internal/abs/filter_test.go @@ -22,11 +22,22 @@ func TestFilterAudioLibraries_KeepsPodcasts(t *testing.T) { } } +// TestFilterAudioLibraries_KeepsAudiobooks verifies that the check reads one +// item, the longest, and keeps the library when that item has audio. func TestFilterAudioLibraries_KeepsAudiobooks(t *testing.T) { dur := 55908.0 numFiles := 138 numTracks := 138 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/libraries/audio-lib/items" { + t.Errorf("path = %q, want /api/libraries/audio-lib/items", r.URL.Path) + } + query := r.URL.Query() + for key, want := range map[string]string{"limit": "1", "sort": "media.duration", "desc": "1"} { + if got := query.Get(key); got != want { + t.Errorf("%s = %q, want %q", key, got, want) + } + } resp := LibraryItemsResponse{ Results: []LibraryItem{{ ID: "item-1", @@ -124,3 +135,19 @@ func TestFilterAudioLibraries_DetectsAudioByNumAudioFiles(t *testing.T) { t.Fatal("expected library with numAudioFiles>0 to be kept") } } + +// TestFilterAudioLibraries_KeepsEmptyLibrary verifies that a book library with +// no items stays in the list: it can get audiobooks later. +func TestFilterAudioLibraries_KeepsEmptyLibrary(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(LibraryItemsResponse{Results: []LibraryItem{}, Total: 0}) + })) + defer srv.Close() + + c := NewClient(srv.URL, "tok") + libs := []Library{{ID: "new-lib", Name: "New", MediaType: "book"}} + result := c.FilterAudioLibraries(context.Background(), libs) + if len(result) != 1 { + t.Fatalf("expected the empty library to be kept, got %d libraries", len(result)) + } +} diff --git a/internal/abs/libraries.go b/internal/abs/libraries.go index ef49ea6..67595f5 100644 --- a/internal/abs/libraries.go +++ b/internal/abs/libraries.go @@ -214,7 +214,7 @@ func strPtr(s string) *string { // 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, "") + return c.getLibraryItems(ctx, libraryID, page, limit, nil) } // GetLibrarySeries returns a paginated list of series in a library. @@ -222,6 +222,8 @@ func (c *Client) GetLibrarySeries(ctx context.Context, libraryID string, page, l query := url.Values{} query.Set("page", strconv.Itoa(page)) query.Set("limit", strconv.Itoa(limit)) + // With no sort, ABS gives the series in no defined order. + query.Set("sort", "name") path := fmt.Sprintf("/api/libraries/%s/series?%s", libraryID, query.Encode()) data, err := c.do(ctx, http.MethodGet, path, nil) if err != nil { @@ -235,12 +237,12 @@ func (c *Client) GetLibrarySeries(ctx context.Context, libraryID string, page, l return &resp, nil } -func (c *Client) getLibraryItems(ctx context.Context, libraryID string, page, limit int, filter string) (*LibraryItemsResponse, error) { +func (c *Client) getLibraryItems(ctx context.Context, libraryID string, page, limit int, extra url.Values) (*LibraryItemsResponse, error) { query := url.Values{} query.Set("page", strconv.Itoa(page)) query.Set("limit", strconv.Itoa(limit)) - if filter != "" { - query.Set("filter", filter) + for key, values := range extra { + query[key] = values } path := fmt.Sprintf("/api/libraries/%s/items?%s", libraryID, query.Encode()) data, err := c.do(ctx, http.MethodGet, path, nil) @@ -344,7 +346,7 @@ func (c *Client) GetSeriesContents(ctx context.Context, libraryID, seriesID stri items := make([]LibraryItem, 0) for page := 0; ; page++ { - resp, err := c.getLibraryItems(ctx, libraryID, page, seriesPageLimit, "series."+encodeLibraryFilterValue(seriesID)) + resp, err := c.getLibraryItems(ctx, libraryID, page, seriesPageLimit, url.Values{"filter": {"series." + encodeLibraryFilterValue(seriesID)}}) if err != nil { return nil, fmt.Errorf("get series items: %w", err) } @@ -450,11 +452,9 @@ func encodeLibraryFilterValue(value string) string { return base64.StdEncoding.EncodeToString([]byte(value)) } -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. +// (ebooks without audio). Podcasts are always kept. A book library is kept if its +// longest item has audio, or if it has no items. // 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 { @@ -512,38 +512,37 @@ func (c *Client) FilterAudioLibraries(ctx context.Context, libs []Library) []Lib return result } -// libraryHasAudio checks if a "book" type library contains any audio items -// by sampling items and checking if any has Duration > 0. -// -// This function assumes libraries contain homogeneous content (all audiobooks or all ebooks). -// If a library contains mixed content, the sampling may not detect audio content if it falls -// outside the sampled range. In practice, ABS typically separates audiobooks and ebooks -// into distinct libraries, so this is not expected to be an issue. +// libraryHasAudio checks if a "book" type library contains audio. It reads the +// item with the longest duration, because an ebook has no duration. A library +// with no items gives true: it can get audiobooks later. func (c *Client) libraryHasAudio(ctx context.Context, libraryID string) (bool, error) { - resp, err := c.GetLibraryItems(ctx, libraryID, 0, audioCheckSampleSize) + resp, err := c.getLibraryItems(ctx, libraryID, 0, 1, url.Values{"sort": {"media.duration"}, "desc": {"1"}}) if err != nil { return false, err } + if len(resp.Results) == 0 { + logger.Debug("library has no items", "libraryID", libraryID) + return true, nil + } - for i, item := range resp.Results { - if item.Media.Duration != nil && *item.Media.Duration > 0 { - logger.Debug("library audio detected", "libraryID", libraryID, "sampleSize", len(resp.Results), "sampleIndex", i, "signal", "media.duration") - return true, nil - } - if item.Media.Metadata.Duration != nil && *item.Media.Metadata.Duration > 0 { - logger.Debug("library audio detected", "libraryID", libraryID, "sampleSize", len(resp.Results), "sampleIndex", i, "signal", "metadata.duration") - return true, nil - } - if item.Media.NumAudioFiles != nil && *item.Media.NumAudioFiles > 0 { - logger.Debug("library audio detected", "libraryID", libraryID, "sampleSize", len(resp.Results), "sampleIndex", i, "signal", "numAudioFiles") - return true, nil - } - if item.Media.NumTracks != nil && *item.Media.NumTracks > 0 { - logger.Debug("library audio detected", "libraryID", libraryID, "sampleSize", len(resp.Results), "sampleIndex", i, "signal", "numTracks") - return true, nil - } + item := resp.Results[0] + if item.Media.Duration != nil && *item.Media.Duration > 0 { + logger.Debug("library audio detected", "libraryID", libraryID, "signal", "media.duration") + return true, nil + } + if item.Media.Metadata.Duration != nil && *item.Media.Metadata.Duration > 0 { + logger.Debug("library audio detected", "libraryID", libraryID, "signal", "metadata.duration") + return true, nil + } + if item.Media.NumAudioFiles != nil && *item.Media.NumAudioFiles > 0 { + logger.Debug("library audio detected", "libraryID", libraryID, "signal", "numAudioFiles") + return true, nil + } + if item.Media.NumTracks != nil && *item.Media.NumTracks > 0 { + logger.Debug("library audio detected", "libraryID", libraryID, "signal", "numTracks") + return true, nil } - logger.Debug("library audio not detected in sample", "libraryID", libraryID, "sampleSize", len(resp.Results)) + logger.Debug("library audio not detected", "libraryID", libraryID) return false, nil } diff --git a/internal/abs/libraries_test.go b/internal/abs/libraries_test.go index 46fadbd..a750d8f 100644 --- a/internal/abs/libraries_test.go +++ b/internal/abs/libraries_test.go @@ -371,13 +371,17 @@ func TestGetLibrarySeriesHTTP(t *testing.T) { if got := r.URL.Query().Get("limit"); got != "50" { t.Errorf("limit = %q, want 50", got) } + if got := r.URL.Query().Get("sort"); got != "name" { + t.Errorf("sort = %q, want name", got) + } w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{ "results": [ { "id": "series-expanse", "name": "The Expanse", - "libraryId": "lib-books-001" + "libraryId": "lib-books-001", + "books": [{"id": "book-1"}, {"id": "book-2"}] } ], "total": 1, @@ -402,6 +406,9 @@ func TestGetLibrarySeriesHTTP(t *testing.T) { if resp.Results[0].ID != "series-expanse" { t.Fatalf("series ID = %q, want series-expanse", resp.Results[0].ID) } + if got := len(resp.Results[0].Books); got != 2 { + t.Fatalf("books = %d, want 2", got) + } } func TestGetSeriesContentsHTTP(t *testing.T) { diff --git a/internal/abs/types.go b/internal/abs/types.go index 4bc9daf..ae6a126 100644 --- a/internal/abs/types.go +++ b/internal/abs/types.go @@ -225,14 +225,21 @@ type SeriesSequence struct { Sequence string `json:"sequence,omitempty"` } -// Series contains series metadata returned by ABS. +// Series contains series metadata returned by ABS. Only the series list of a +// library has the books. 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"` + 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,omitempty"` +} + +// SeriesBook is a book in the series list of a library. +type SeriesBook struct { + ID string `json:"id"` } // SeriesContents combines series metadata with the library items in that series. diff --git a/internal/app/bookmarks.go b/internal/app/bookmarks.go index 570b9c0..b21106f 100644 --- a/internal/app/bookmarks.go +++ b/internal/app/bookmarks.go @@ -225,14 +225,18 @@ func (m Model) fetchBookDetailCmd(item abs.LibraryItem) tea.Cmd { } func (m Model) detailLoadCmds(item abs.LibraryItem, navCmd tea.Cmd) []tea.Cmd { - cmds := []tea.Cmd{navCmd, m.fetchBookmarksCmd(item.ID)} - if item.MediaType == "podcast" { - return append(cmds, m.fetchEpisodesCmd(item.ID)) - } - if item.MediaType == "book" { - return append(cmds, m.fetchBookDetailCmd(item)) - } - return cmds + return []tea.Cmd{navCmd, m.fetchBookmarksCmd(item.ID), m.detailItemCmd(item)} +} + +// detailItemCmd loads the episodes of a podcast or the full item of a book. +func (m Model) detailItemCmd(item abs.LibraryItem) tea.Cmd { + switch item.MediaType { + case "podcast": + return m.fetchEpisodesCmd(item.ID) + case "book": + return m.fetchBookDetailCmd(item) + } + return nil } // nextChapter returns the start time of the next chapter after current position (book-global). diff --git a/internal/app/e2e_helpers_test.go b/internal/app/e2e_helpers_test.go index cb7d258..1893a9d 100644 --- a/internal/app/e2e_helpers_test.go +++ b/internal/app/e2e_helpers_test.go @@ -94,6 +94,13 @@ func testPodcastItem(id, title string) abs.LibraryItem { } } +// testSeries is the series of the book library of the mock server. A scan of +// the library finds testScannedSeries. +var ( + testSeries = abs.Series{ID: "ser-001", Name: "Dystopias", LibraryID: "lib-001"} + testScannedSeries = abs.Series{ID: "ser-002", Name: "Utopias", LibraryID: "lib-001"} +) + func testBookmark(title string, seconds float64) abs.Bookmark { return abs.Bookmark{ Title: title, @@ -325,6 +332,18 @@ func newFullMockABSServer(log *apiLog, state *e2eServerState) *httptest.Server { } _ = json.NewEncoder(w).Encode(resp) + // --- Series of the book library --- + case r.Method == http.MethodGet && r.URL.Path == "/api/libraries/lib-001/series": + results := []abs.Series{testSeries} + if state.getLastScan() != 0 { + results = append(results, testScannedSeries) + } + resp := abs.LibrarySeriesResponse{Results: results, Total: len(results), Limit: 50} + _ = json.NewEncoder(w).Encode(resp) + + case r.Method == http.MethodGet && r.URL.Path == "/api/libraries/lib-001/series/"+testSeries.ID: + _ = json.NewEncoder(w).Encode(testSeries) + // --- Library items (books) --- case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/api/libraries/lib-001/items"): resp := abs.LibraryItemsResponse{ diff --git a/internal/app/e2e_test.go b/internal/app/e2e_test.go index 119d9cc..b60925b 100644 --- a/internal/app/e2e_test.go +++ b/internal/app/e2e_test.go @@ -880,6 +880,22 @@ func e2eSaveBookmarkTitle(m Model, state *e2eServerState) string { return state.getBookmarks("item-001")[0].Title } +// TestE2E_ScanDuringBookmarkTitleEditKeepsTheEdit verifies that the reload of +// the detail screen after a scan does not close the bookmark title editor. +func TestE2E_ScanDuringBookmarkTitleEditKeepsTheEdit(t *testing.T) { + m, _ := e2eDetailWithBookmark(t) + m, _ = e2ePressKey(m, 'e') + if !m.detail.EditingBookmark() { + t.Fatal("the bookmark editor did not open") + } + + res, cmd := m.Update(LibraryScannedMsg{LibraryID: m.detail.Item().LibraryID}) + m, _ = feedCmdWithin(res.(Model), cmd, slowCmdWait) + if !m.detail.EditingBookmark() { + t.Error("the reload after the scan closed the bookmark editor") + } +} + // TestE2E_BookmarkTitleEditGetsEachKey verifies that the bookmark title editor // gets each key during a playback. Outside the editor, these keys have a // global function or a playback function. @@ -2573,6 +2589,65 @@ func TestE2E_PaletteShowsResultsWhenSnapshotIsBuilt(t *testing.T) { } } +// TestE2E_PaletteSearchesEachLibrary verifies that the palette search shows +// the matches of the current library first, then the matches of each other +// library below a header with its name. +func TestE2E_PaletteSearchesEachLibrary(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) + for _, lib := range m.home.Libraries() { + if err := m.searchCache.Prepare(context.Background(), lib.ID, lib.MediaType); err != nil { + t.Fatalf("Prepare(%s) error: %v", lib.ID, err) + } + } + + res, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlP}) + m = res.(Model) + m = e2eTypeString(m, "test") + view := m.palette.View() + book := strings.Index(view, "The Great Gatsby") + header := strings.Index(view, "PODCASTS") + podcast := strings.Index(view, "Tech Talk Daily") + if book < 0 || header < 0 || podcast < 0 || book > header || header > podcast { + t.Errorf("the palette does not show the book, then the header of the podcast library, then the podcast\n%s", view) + } +} + +// TestE2E_PaletteSearchShowsIndexBuild verifies that the palette search shows +// a row while the index of a library is not ready. +func TestE2E_PaletteSearchShowsIndexBuild(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) + if err := m.searchCache.Prepare(context.Background(), "lib-001", "book"); err != nil { + t.Fatalf("Prepare() error: %v", err) + } + m.searchCache.Invalidate("lib-pods") + + items := m.contentSearchFunc()("test") + if len(items) == 0 { + t.Fatal("the search found no item") + } + if last := items[len(items)-1]; !last.IsHeader || last.Label != "Building index…" { + t.Errorf("last row = %+v, want the header Building index…", last) + } + if items[0].IsHeader { + t.Errorf("first row = %+v, want an item of the current library", items[0]) + } +} + // TestE2E_MetadataSaveBuildsSearchSnapshot verifies that a metadata save // builds the search snapshot again: the save clears the snapshots. func TestE2E_MetadataSaveBuildsSearchSnapshot(t *testing.T) { @@ -2674,6 +2749,7 @@ func TestE2E_PaletteScanLibraryReloadsAfterTheScan(t *testing.T) { if scanCmd == nil { t.Fatal("Scan Library returns no command") } + assertViewContains(t, m, "Scanning Audiobooks") m, reloadCmd := feedCmdWithin(m, scanCmd, slowCmdWait) if got := log.count(http.MethodPost, "/api/libraries/lib-001/scan"); got != 1 { @@ -2682,8 +2758,102 @@ func TestE2E_PaletteScanLibraryReloadsAfterTheScan(t *testing.T) { if m.err.HasError() { t.Fatalf("error after the scan: %v", m.err.Error()) } + if strings.Contains(m.View(), "Scanning") { + t.Error("the view shows the scan box after the end of the scan") + } feedCmdChain(m, reloadCmd, 5) if got := log.count(http.MethodGet, "/api/libraries/lib-001/personalized"); got <= loads { t.Errorf("home loads = %d, want more than %d after the scan", got, loads) } } + +// TestE2E_PaletteScanLibraryReloadsSeriesScreens verifies that a scan loads +// the series screen of the library again, and the series list in the back +// stack. The series list shows the series that the scan finds. +func TestE2E_PaletteScanLibraryReloadsSeriesScreens(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) + res, cmd := m.Update(library.NavigateSeriesListMsg{LibraryID: "lib-001", LibraryName: "Audiobooks"}) + m = res.(Model) + m, _ = feedCmd(m, cmd) + m, cmd = e2ePressSpecial(m, tea.KeyEnter) + m = feedCmdChain(m, cmd, 3) + assertScreen(t, m, ScreenSeries) + seriesPath := "/api/libraries/lib-001/series/" + testSeries.ID + loads := log.count(http.MethodGet, seriesPath) + + res, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlP}) + m = res.(Model) + m = e2eTypeString(m, "scan") + m, _ = e2ePressSpecial(m, tea.KeyEnter) + m, scanCmd := e2ePressSpecial(m, tea.KeyEnter) + m, reloadCmd := feedCmdWithin(m, scanCmd, slowCmdWait) + if got := log.count(http.MethodPost, "/api/libraries/lib-001/scan"); got != 1 { + t.Fatalf("scan requests = %d, want 1", got) + } + m = feedCmdChain(m, reloadCmd, 5) + + if got := log.count(http.MethodGet, seriesPath); got <= loads { + t.Errorf("series loads = %d, want more than %d after the scan", got, loads) + } + if !strings.Contains(m.seriesList.View(), testScannedSeries.Name) { + t.Errorf("the series list does not show %q after the scan", testScannedSeries.Name) + } +} + +// TestE2E_PaletteRefreshLoadsLibrariesAgain verifies that the palette entry +// Refresh clears the persistent cache, and reads the library list and the home +// shelves from the server again. +func TestE2E_PaletteRefreshLoadsLibrariesAgain(t *testing.T) { + log := &apiLog{} + state := &e2eServerState{bookmarks: make(map[string][]abs.Bookmark)} + srv := newFullMockABSServer(log, state) + defer srv.Close() + libraryLoads := func() int { + n := 0 + for _, r := range log.get() { + if r.Method == http.MethodGet && r.Path == "/api/libraries" { + n++ + } + } + return n + } + + 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) + client := cache.NewClient(abs.NewClient(srv.URL, "jwt-token-e2e"), cacheStore) + m := NewWithPlayer(config.Default(), nil, client, cacheStore, &mockPlayer{}) + m = e2eSetSize(m, 120, 40) + m, _ = feedCmdWithin(m, m.home.Init(), slowCmdWait) + libraries := libraryLoads() + shelves := log.count(http.MethodGet, "/api/libraries/lib-001/personalized") + + res, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlP}) + m = res.(Model) + m = e2eTypeString(m, "refresh") + m, _ = e2ePressSpecial(m, tea.KeyEnter) + m, refreshCmd := e2ePressSpecial(m, tea.KeyEnter) + if refreshCmd == nil { + t.Fatal("Refresh returns no command") + } + m, reloadCmd := feedCmdWithin(m, refreshCmd, slowCmdWait) + feedCmdWithin(m, reloadCmd, slowCmdWait) + + if got := libraryLoads(); got <= libraries { + t.Errorf("library list loads = %d, want more than %d after Refresh", got, libraries) + } + if got := log.count(http.MethodGet, "/api/libraries/lib-001/personalized"); got <= shelves { + t.Errorf("home loads = %d, want more than %d after Refresh", got, shelves) + } +} diff --git a/internal/app/messages.go b/internal/app/messages.go index 60e009b..8b5bdc9 100644 --- a/internal/app/messages.go +++ b/internal/app/messages.go @@ -158,11 +158,17 @@ type SeriesContinueMsg struct { } // LibraryScannedMsg is sent after the end of a scan of a library on the -// server. The screens then load the data of the library again. +// server. The screens then load the data of the library again. Err is the +// error of a scan that failed. type LibraryScannedMsg struct { LibraryID string + Err error } +// CacheClearedMsg is sent after the palette entry Refresh clears the cache. +// The screens and the library list then load again. +type CacheClearedMsg struct{} + // PrewarmDoneMsg is sent after cache pre-warming completes. No action needed, // just used to keep the command chain alive. type PrewarmDoneMsg struct{} diff --git a/internal/app/model.go b/internal/app/model.go index 1fcc184..3a5d12b 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -27,6 +27,7 @@ import ( "github.com/Thelost77/pine/internal/ui" "github.com/Thelost77/pine/internal/ui/components" "github.com/charmbracelet/bubbles/key" + "github.com/charmbracelet/bubbles/spinner" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" ) @@ -107,6 +108,11 @@ type Model struct { palette components.Palette + // scanStatus is the text of the box of a running scan. It is empty when + // no scan runs. + scanStatus string + scanSpinner spinner.Model + lastPlayedTitle string lastPlayedTrackID string lastPlayedAuthors []string @@ -158,6 +164,7 @@ func NewWithPlayer(cfg config.Config, store *db.Store, client *cache.Client, cac mprisLink: &mprisLink{}, mprisState: &MprisState{}, palette: palette, + scanSpinner: spinner.New(spinner.WithSpinner(spinner.MiniDot), spinner.WithStyle(styles.Accent)), } } @@ -589,6 +596,18 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case serieslist.BackMsg: return m.back() + // A load reaches its screen also behind the active screen: a scan loads + // the screens in the back stack again. + case serieslist.LoadedMsg: + var cmd tea.Cmd + m.seriesList, cmd = m.seriesList.Update(msg) + return m, cmd + + case series.LoadedMsg: + var cmd tea.Cmd + m.series, cmd = m.series.Update(msg) + return m, cmd + case detail.MarkFinishedCmd: return m.handleMarkFinished(msg) @@ -625,12 +644,34 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, tea.Batch(m.home.ReloadCmd(), m.library.ReloadCmd(), m.prewarmCacheCmd()) case LibraryScannedMsg: + m.scanStatus = "" + if msg.Err != nil { + return m.Update(components.ErrMsg{Err: msg.Err}) + } m.home.InvalidateLibrary(msg.LibraryID) m.library.InvalidateLibrary(msg.LibraryID) if m.searchCache != nil { m.searchCache.Invalidate(msg.LibraryID) } - return m, tea.Batch(m.home.ReloadCmd(), m.library.ReloadCmd(), m.prewarmCacheCmd()) + cmd := tea.Batch(m.home.ReloadCmd(), m.library.ReloadCmd(), m.prewarmCacheCmd(), m.reloadOpenScreensCmd(msg.LibraryID)) + return m, cmd + + case CacheClearedMsg: + for _, lib := range m.home.Libraries() { + m.library.InvalidateLibrary(lib.ID) + } + // The warm-up of the search index starts with home.PersonalizedMsg. + cmd := tea.Batch(m.home.RefreshCmd(), m.library.ReloadCmd(), m.reloadOpenScreensCmd("")) + return m, cmd + + case spinner.TickMsg: + // The ticks end with the scan. + if m.scanStatus == "" { + return m, nil + } + var cmd tea.Cmd + m.scanSpinner, cmd = m.scanSpinner.Update(msg) + return m, cmd case detail.SeekToBookmarkCmd: return m.handleSeekToBookmark(msg) @@ -786,11 +827,9 @@ 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() - } + // The palette searches each library, so it shows the results of its + // query again when the snapshot of a library is ready. + m.palette.Refresh() return m.updateScreen(msg) case SleepTimerExpiredMsg: @@ -1137,9 +1176,9 @@ func (m Model) checkUnauthorized(err error) (Model, tea.Cmd, bool) { } // 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. +// from a snapshot that is ready, so it returns a command that builds the +// snapshot of each library that has none. CacheReadyMsg then shows the results +// of the query. func (m *Model) openGlobalPalette() tea.Cmd { playerItems, navItems := m.buildStaticPaletteItems() contextItems := m.buildContextPaletteItems() @@ -1151,45 +1190,76 @@ func (m *Model) openGlobalPalette() tea.Cmd { items = append(items, navItems...) m.palette.Open(items, m.contentSearchFunc()) - libID, libMediaType := m.currentLibraryForSearch() - if m.searchCache == nil || libID == "" { + if m.searchCache == nil { return nil } - if _, ok := m.searchCache.TryGetAll(libID, libMediaType); ok { - return nil + var cmds []tea.Cmd + for _, lib := range m.searchLibraries() { + if _, ok := m.searchCache.TryGetAll(lib.ID, lib.MediaType); !ok { + cmds = append(cmds, m.searchCache.PrebuildCmd(lib.ID, lib.MediaType)) + } + } + return tea.Batch(cmds...) +} + +// searchLibraries returns the libraries of the palette search: the library of +// the current screen first, then the other libraries. +func (m Model) searchLibraries() []abs.Library { + libID, libMediaType := m.currentLibraryForSearch() + var libs []abs.Library + if libID != "" { + libs = append(libs, abs.Library{ID: libID, Name: m.libraryName(libID), MediaType: libMediaType}) } - return m.searchCache.PrebuildCmd(libID, libMediaType) + for _, lib := range m.home.Libraries() { + if lib.ID != libID { + libs = append(libs, lib) + } + } + return libs } +// contentSearchFunc searches the library of the current screen first, then +// each other library. The items of a different library are below a header with +// its name. A row at the end shows that an index is not ready. func (m Model) contentSearchFunc() components.SearchFunc { return func(query string) []components.PaletteItem { if m.searchCache == nil { return nil } - libID, libMediaType := m.currentLibraryForSearch() - if libID == "" { - return nil - } + currentID, _ := m.currentLibraryForSearch() ctx := context.Background() - results, err := m.searchCache.Search(ctx, libID, libMediaType, query) - if err != nil || len(results) == 0 { - return nil - } - items := make([]components.PaletteItem, 0, len(results)) - for _, res := range results { - label := res.Media.Metadata.Title - if res.MediaType == "podcast" && res.RecentEpisode != nil { - label = res.RecentEpisode.Title + " — " + res.Media.Metadata.Title + var items []components.PaletteItem + building := false + for _, lib := range m.searchLibraries() { + if _, ok := m.searchCache.TryGetAll(lib.ID, lib.MediaType); !ok { + building = true + } + // With no ready index, Search builds it in the background. + results, err := m.searchCache.Search(ctx, lib.ID, lib.MediaType, query) + if err != nil || len(results) == 0 { + continue + } + if lib.ID != currentID { + items = append(items, components.PaletteItem{Label: lib.Name, IsHeader: true}) + } + for _, res := range results { + label := res.Media.Metadata.Title + if res.MediaType == "podcast" && res.RecentEpisode != nil { + label = res.RecentEpisode.Title + " — " + res.Media.Metadata.Title + } + itemCopy := res + items = append(items, components.PaletteItem{ + Label: label, + Action: components.ActionContentNavigate, + PlayAction: components.ActionPlayDirect, + LibraryID: res.LibraryID, + ItemID: res.ID, + Data: itemCopy, + }) } - itemCopy := res - items = append(items, components.PaletteItem{ - Label: label, - Action: components.ActionContentNavigate, - PlayAction: components.ActionPlayDirect, - LibraryID: res.LibraryID, - ItemID: res.ID, - Data: itemCopy, - }) + } + if building { + items = append(items, components.PaletteItem{Label: "Building index…", IsHeader: true}) } return items } @@ -1213,6 +1283,12 @@ func (m Model) currentLibraryForSearch() (libID, libMediaType string) { return item.LibraryID, item.MediaType } return m.home.SelectedLibraryID(), m.home.SelectedLibraryMediaType() + case ScreenSessions: + // The sessions of all items have no library. + if lib, ok := m.libraryByID(m.sessions.LibraryID()); ok { + return lib.ID, lib.MediaType + } + return m.home.SelectedLibraryID(), m.home.SelectedLibraryMediaType() case ScreenHome: return m.home.SelectedLibraryID(), m.home.SelectedLibraryMediaType() default: @@ -1222,28 +1298,42 @@ func (m Model) currentLibraryForSearch() (libID, libMediaType string) { // libraryName returns the name of a library, or an empty string. func (m Model) libraryName(id string) string { + lib, _ := m.libraryByID(id) + return lib.Name +} + +// libraryByID returns a library of the library list of the home screen. +func (m Model) libraryByID(id string) (abs.Library, bool) { for _, lib := range m.home.Libraries() { if lib.ID == id { - return lib.Name + return lib, true } } - return "" + return abs.Library{}, false } func (m Model) buildStaticPaletteItems() (player, nav []components.PaletteItem) { nav = []components.PaletteItem{ {Label: "Navigation", IsHeader: true}, {Label: "Go Home", Action: components.ActionGoHome}, - {Label: "Go Library", Action: components.ActionGoLibrary}, } + if m.screen != ScreenLibrary { + nav = append(nav, components.PaletteItem{Label: "Go Library", Action: components.ActionGoLibrary}) + } + libID, mediaType := m.currentLibraryForSearch() // Only a book library has series. The series list is the target of the entry. - if libID, mediaType := m.currentLibraryForSearch(); mediaType == "book" && m.screen != ScreenSeriesList { + if mediaType == "book" && m.screen != ScreenSeriesList { nav = append(nav, components.PaletteItem{Label: "Browse Series", Action: components.ActionBrowseSeries, LibraryID: libID, Payload: m.libraryName(libID)}) } + scanLabel := "Scan Library" + if name := m.libraryName(libID); name != "" { + scanLabel += ": " + name + } nav = append(nav, components.PaletteItem{Label: "Listening History", Action: components.ActionShowSessions}, components.PaletteItem{Label: "Library", IsHeader: true}, - components.PaletteItem{Label: "Scan Library", Action: components.ActionScanLibrary}, + components.PaletteItem{Label: scanLabel, Action: components.ActionScanLibrary}, + components.PaletteItem{Label: "Refresh", Action: components.ActionRefresh}, ) if !m.isPlaying() { @@ -1341,6 +1431,8 @@ func (m Model) handlePaletteAction(action components.PaletteAction, payload, lib case components.ActionGoHome: return m.navigate(ScreenHome) case components.ActionGoLibrary: + libID, _ := m.currentLibraryForSearch() + m.library.Configure(libID, m.home.Libraries()) return m.navigate(ScreenLibrary) case components.ActionShowSessions: if entry, ok := data.(detail.AddToQueueCmd); ok { @@ -1642,7 +1734,28 @@ func (m Model) handlePaletteAction(action components.PaletteAction, payload, lib case components.ActionSwitchLibrary: return m, nil case components.ActionScanLibrary: - return m, m.scanLibraryCmd() + scanCmd := m.scanLibraryCmd() + if m.scanStatus != "" || scanCmd == nil { + return m, nil + } + libID, _ := m.currentLibraryForSearch() + name := m.libraryName(libID) + if name == "" { + name = "library" + } + m.scanStatus = "Scanning " + name + "…" + // The tick is first, because feedCmdWithin of the tests runs each + // command of a batch and gives the command of the last one. + return m, tea.Batch(m.scanSpinner.Tick, scanCmd) + case components.ActionRefresh: + if m.client == nil { + return m, nil + } + client := m.client + return m, func() tea.Msg { + client.Invalidate() + return CacheClearedMsg{} + } case components.ActionDeleteItem: if msg, ok := data.(detail.ShowDeleteConfirmMsg); ok && m.screen == ScreenDetail { m.detail, _ = m.detail.Update(msg) @@ -1652,25 +1765,25 @@ func (m Model) handlePaletteAction(action components.PaletteAction, payload, lib return m, nil } +// prewarmCacheCmd builds the search snapshot of each library, the library of +// the current screen first. func (m Model) prewarmCacheCmd() tea.Cmd { + cache := m.searchCache + libs := m.searchLibraries() return func() tea.Msg { - cache := m.searchCache if cache == nil { return PrewarmDoneMsg{} } - libID := m.home.SelectedLibraryID() - libMediaType := m.home.SelectedLibraryMediaType() - if libID == "" { - return PrewarmDoneMsg{} + for _, lib := range libs { + _ = cache.Prepare(context.Background(), lib.ID, lib.MediaType) } - _ = cache.Prepare(context.Background(), libID, libMediaType) return PrewarmDoneMsg{} } } // scanLibraryCmd scans the library of the current screen on the server. At the // end of the scan, the cache client clears the cache, and LibraryScannedMsg -// loads the screens again. +// closes the scan box and loads the screens again, or shows the error. func (m Model) scanLibraryCmd() tea.Cmd { libraryID, _ := m.currentLibraryForSearch() if m.client == nil || libraryID == "" { @@ -1684,12 +1797,36 @@ func (m Model) scanLibraryCmd() tea.Cmd { if abs.IsHTTPStatus(err, http.StatusForbidden) { err = fmt.Errorf("ABS user does not have the admin permission to scan: %w", err) } - return components.ErrMsg{Err: fmt.Errorf("failed to scan library: %w", err)} + return LibraryScannedMsg{LibraryID: libraryID, Err: fmt.Errorf("failed to scan library: %w", err)} } return LibraryScannedMsg{LibraryID: libraryID} } } +// reloadOpenScreensCmd loads the open series list, series screen, and detail +// screen of a library again. With an empty libraryID, it loads them for each +// library. +func (m *Model) reloadOpenScreensCmd(libraryID string) tea.Cmd { + inLibrary := func(id string) bool { + return libraryID == "" || id == libraryID + } + var cmds []tea.Cmd + if m.screenOpen(ScreenSeriesList) && inLibrary(m.seriesList.SelectedLibraryID()) { + cmds = append(cmds, m.seriesList.ReloadCmd()) + } + if m.screenOpen(ScreenSeries) && inLibrary(m.series.LibraryID()) { + cmds = append(cmds, m.series.Init()) + } + if item := m.detail.Item(); m.screenOpen(ScreenDetail) && inLibrary(item.LibraryID) { + cmds = append(cmds, m.detailItemCmd(item)) + // A load of the bookmarks closes the bookmark title editor. + if !m.detail.EditingBookmark() { + cmds = append(cmds, m.fetchBookmarksCmd(item.ID)) + } + } + return tea.Batch(cmds...) +} + func (m Model) handleDeleteItem(cmd detail.DeleteItemCmd) (Model, tea.Cmd) { if m.client == nil { return m, nil diff --git a/internal/app/model_test.go b/internal/app/model_test.go index 762f972..c42813c 100644 --- a/internal/app/model_test.go +++ b/internal/app/model_test.go @@ -24,6 +24,7 @@ import ( "github.com/Thelost77/pine/internal/screens/metadataedit" "github.com/Thelost77/pine/internal/screens/series" "github.com/Thelost77/pine/internal/screens/serieslist" + "github.com/Thelost77/pine/internal/screens/sessions" "github.com/Thelost77/pine/internal/ui" "github.com/Thelost77/pine/internal/ui/components" tea "github.com/charmbracelet/bubbletea" @@ -2517,6 +2518,14 @@ func TestPaletteBrowseSeriesOpensBookLibraryOfScreen(t *testing.T) { m.seriesList = serieslist.New(m.styles, m.client, "lib-a", "A") m.screen = ScreenSeriesList }, "", ""}, + {"sessions of a book", homeOnPodcasts, func(m *Model) { + m.sessions = sessions.New(m.styles, m.client, sessions.Target{ItemID: "b-1", LibraryID: "lib-b"}, "") + m.screen = ScreenSessions + }, "lib-b", "B"}, + {"sessions of all items", homeOnBooks, func(m *Model) { + m.sessions = sessions.New(m.styles, m.client, sessions.Target{}, "") + m.screen = ScreenSessions + }, "lib-a", "A"}, } for _, tt := range tests { @@ -2558,6 +2567,180 @@ func TestPaletteBrowseSeriesOpensBookLibraryOfScreen(t *testing.T) { } } +// TestPaletteGoLibraryOpensLibraryOfScreen verifies that Go Library of the +// palette opens the library of the current screen, also before the library +// screen opens for the first time. The library screen shows no Go Library. +func TestPaletteGoLibraryOpensLibraryOfScreen(t *testing.T) { + // The home screen shows the first library. + libs := []abs.Library{ + {ID: "lib-a", Name: "A", MediaType: "book"}, + {ID: "lib-b", Name: "B", MediaType: "book"}, + } + book := abs.LibraryItem{ID: "b-1", LibraryID: "lib-b", MediaType: "book"} + + tests := []struct { + name string + setup func(m *Model) + wantLib string + }{ + {"home on a book library", func(m *Model) { m.screen = ScreenHome }, "lib-a"}, + {"detail of a book of a different library", func(m *Model) { + m.detail = detail.New(m.styles, book) + m.screen = ScreenDetail + }, "lib-b"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := newTestModelAuthenticated() + m.home, _ = m.home.Update(home.PersonalizedMsg{Libraries: libs}) + tt.setup(&m) + + var goLibrary *components.PaletteItem + _, nav := m.buildStaticPaletteItems() + for _, item := range nav { + if item.Action == components.ActionGoLibrary { + goLibrary = &item + } + } + if goLibrary == nil { + t.Fatal("the palette has no Go Library") + } + m, _ = m.handlePaletteAction(goLibrary.Action, goLibrary.Payload, goLibrary.LibraryID, goLibrary.ItemID, goLibrary.Data) + if m.screen != ScreenLibrary { + t.Errorf("screen = %v, want the library", m.screen) + } + if got := m.library.SelectedLibraryID(); got != tt.wantLib { + t.Errorf("library = %q, want %q", got, tt.wantLib) + } + }) + } + + t.Run("library screen", func(t *testing.T) { + m := newTestModelAuthenticated() + m.home, _ = m.home.Update(home.PersonalizedMsg{Libraries: libs}) + m.library.Configure("lib-b", libs) + m.screen = ScreenLibrary + + _, nav := m.buildStaticPaletteItems() + for _, item := range nav { + if item.Action == components.ActionGoLibrary { + t.Error("the library screen has Go Library") + } + } + }) +} + +// TestScanReloadBlocksNextPageOfSeriesList verifies that the reload after a +// scan marks the open series list as loading, so that the list starts no load +// of a next page that can mix an old page into the new list. +func TestScanReloadBlocksNextPageOfSeriesList(t *testing.T) { + m := newTestModelAuthenticated() + m.seriesList = serieslist.New(m.styles, m.client, "lib-a", "A") + m.seriesList, _ = m.seriesList.Update(serieslist.LoadedMsg{LibraryID: "lib-a", Results: []abs.Series{{ID: "ser-1", Name: "Dune"}}, Total: 120}) + m.backStack = []Screen{ScreenHome} + m.screen = ScreenSeriesList + if m.seriesList.Loading() { + t.Fatal("the series list loads before the scan") + } + + res, _ := m.Update(LibraryScannedMsg{LibraryID: "lib-a"}) + m = res.(Model) + if !m.seriesList.Loading() { + t.Error("the series list does not load after the scan") + } + + // The answer of a load from before the scan does not change the list. + res, _ = m.Update(serieslist.LoadedMsg{LibraryID: "lib-a", Results: []abs.Series{{ID: "ser-9", Name: "Old Page"}}, Total: 120, Page: 1}) + m = res.(Model) + m.width, m.height = 100, 30 + m.propagateSize() + if containsString(m.seriesList.View(), "Old Page") { + t.Error("the series list shows a page of a load from before the scan") + } +} + +// TestSeriesLoadedMsgReachesScreenBehindActiveScreen verifies that a load of +// the series list or of a series reaches its screen model also when a +// different screen is active: a scan loads the screens in the back stack again. +func TestSeriesLoadedMsgReachesScreenBehindActiveScreen(t *testing.T) { + t.Run("series list behind the series screen", func(t *testing.T) { + m := newTestModelAuthenticated() + m.seriesList = serieslist.New(m.styles, m.client, "lib-a", "A") + m.series = series.New(m.styles, m.client, "lib-a", "ser-1", "") + m.backStack = []Screen{ScreenHome, ScreenSeriesList} + m.screen = ScreenSeries + + m.width, m.height = 100, 30 + m.propagateSize() + + res, _ := m.Update(serieslist.LoadedMsg{LibraryID: "lib-a", Results: []abs.Series{{ID: "ser-1", Name: "Dune"}}, Total: 1}) + m = res.(Model) + if m.seriesList.Loading() || !containsString(m.seriesList.View(), "Dune") { + t.Errorf("the series list did not get the loaded page\n%s", m.seriesList.View()) + } + }) + + t.Run("series behind the detail screen", func(t *testing.T) { + m := newTestModelAuthenticated() + m.series = series.New(m.styles, m.client, "lib-a", "ser-1", "") + m.detail = detail.New(m.styles, abs.LibraryItem{ID: "b-1", LibraryID: "lib-a", MediaType: "book"}) + m.backStack = []Screen{ScreenHome, ScreenSeries} + m.screen = ScreenDetail + + m.width, m.height = 100, 30 + m.propagateSize() + + res, _ := m.Update(series.LoadedMsg{SeriesID: "ser-1", Contents: abs.SeriesContents{ + Series: abs.Series{ID: "ser-1", Name: "Dune"}, + Items: []abs.LibraryItem{{ID: "b-1", Media: abs.Media{Metadata: abs.MediaMetadata{Title: "Dune Messiah"}}}}, + }}) + m = res.(Model) + if m.series.Loading() || !containsString(m.series.View(), "Dune Messiah") { + t.Errorf("the series screen did not get the loaded series\n%s", m.series.View()) + } + }) +} + +// TestPaletteScanLibraryShowsScanBox verifies that Scan Library shows the box +// of the scan, that a second Scan Library does nothing while the scan runs, +// and that the end of a scan that failed closes the box and shows the error. +func TestPaletteScanLibraryShowsScanBox(t *testing.T) { + m := newTestModelAuthenticated() + m.home, _ = m.home.Update(home.PersonalizedMsg{Libraries: []abs.Library{{ID: "lib-a", Name: "A", MediaType: "book"}}}) + + var scan *components.PaletteItem + _, nav := m.buildStaticPaletteItems() + for _, item := range nav { + if item.Action == components.ActionScanLibrary { + scan = &item + } + } + if scan == nil || scan.Label != "Scan Library: A" { + t.Fatalf("Scan Library entry = %+v, want the label %q", scan, "Scan Library: A") + } + + m, cmd := m.handlePaletteAction(components.ActionScanLibrary, "", "", "", nil) + if cmd == nil { + t.Fatal("Scan Library returns no command") + } + if m.scanStatus != "Scanning A…" { + t.Errorf("scan status = %q, want %q", m.scanStatus, "Scanning A…") + } + if _, cmd := m.handlePaletteAction(components.ActionScanLibrary, "", "", "", nil); cmd != nil { + t.Error("a second Scan Library returns a command while a scan runs") + } + + res, _ := m.Update(LibraryScannedMsg{LibraryID: "lib-a", Err: errors.New("failed to scan library: boom")}) + m = res.(Model) + if m.scanStatus != "" { + t.Errorf("scan status = %q after the scan failed, want none", m.scanStatus) + } + if !m.err.HasError() { + t.Error("no error banner after the scan failed") + } +} + // 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 diff --git a/internal/app/navigation.go b/internal/app/navigation.go index 2488ce8..2a6a02c 100644 --- a/internal/app/navigation.go +++ b/internal/app/navigation.go @@ -1,6 +1,8 @@ package app import ( + "slices" + "github.com/Thelost77/pine/internal/logger" tea "github.com/charmbracelet/bubbletea" ) @@ -41,6 +43,11 @@ func (m Model) BackStack() []Screen { return cp } +// screenOpen reports whether s is the active screen or is in the back stack. +func (m Model) screenOpen(s Screen) bool { + return m.screen == s || slices.Contains(m.backStack, s) +} + // screenHeight returns the available height for screen content. func (m Model) screenHeight() int { h := m.height - headerHeight diff --git a/internal/app/render.go b/internal/app/render.go index 04f60ea..6392a88 100644 --- a/internal/app/render.go +++ b/internal/app/render.go @@ -45,6 +45,10 @@ func (m Model) View() string { content = strings.Join(normalizeOverlayCanvas(content, w, m.height), "\n") } + // The chapter overlay, the confirmation dialog, and the palette cover the + // scan box. + content = m.overlayScanBox(content) + if m.chapterOverlayVisible { content = m.overlayChapterModal(content) } @@ -378,6 +382,43 @@ func (m Model) overlayChapterModal(content string) string { return strings.Join(baseLines, "\n") } +// overlayScanBox shows the box of a running scan at the right edge, below the +// header and the error banner. +func (m Model) overlayScanBox(content string) string { + if m.scanStatus == "" { + return content + } + overlay := m.styles.Border.Padding(0, 1).Render(m.scanSpinner.View() + " " + m.scanStatus) + if m.width <= 0 || m.height <= 0 { + return lipgloss.JoinVertical(lipgloss.Left, content, "", overlay) + } + + w := normalizeViewWidth(m.width) + baseLines := normalizeOverlayCanvas(content, w, m.height) + overlayLines := strings.Split(overlay, "\n") + overlayWidth := lipgloss.Width(overlay) + if overlayWidth <= 0 || len(overlayLines) == 0 { + return content + } + + x := max(0, w-overlayWidth) + y := headerHeight + if m.err.HasError() { + y++ + } + for i, line := range overlayLines { + if y+i >= len(baseLines) { + break + } + lineWidth := lipgloss.Width(line) + left := ansi.Truncate(baseLines[y+i], x, "") + right := ansi.TruncateLeft(baseLines[y+i], x+lineWidth, "") + baseLines[y+i] = left + line + right + } + + return strings.Join(baseLines, "\n") +} + func (m Model) viewChapterOverlay() string { if !m.chapterOverlayVisible { return "" diff --git a/internal/app/render_test.go b/internal/app/render_test.go index dc23da6..addbae1 100644 --- a/internal/app/render_test.go +++ b/internal/app/render_test.go @@ -1,6 +1,8 @@ package app import ( + "errors" + "fmt" "strings" "testing" @@ -10,6 +12,7 @@ import ( "github.com/Thelost77/pine/internal/screens/library" "github.com/Thelost77/pine/internal/screens/metadataedit" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" ) func TestViewRendersChapterOverlay(t *testing.T) { @@ -360,3 +363,83 @@ func TestViewHidesCaptionWithoutCues(t *testing.T) { t.Fatal("View() showed caption text without cues") } } + +// TestViewShowsScanBox verifies that the view shows the box of a running scan +// at the right edge below the header, and no box when no scan runs. +func TestViewShowsScanBox(t *testing.T) { + m := newTestModelAuthenticated() + m.width = 100 + m.height = 30 + m.propagateSize() + if containsString(m.View(), "Scanning") { + t.Fatal("the view shows a scan box with no scan") + } + + m.scanStatus = "Scanning Audiobooks…" + lines := strings.Split(m.View(), "\n") + row := -1 + for i, line := range lines { + if strings.Contains(line, m.scanStatus) { + row = i + break + } + } + if row < 0 { + t.Fatalf("the view does not show the scan status\n%s", strings.Join(lines, "\n")) + } + if row < headerHeight { + t.Errorf("the scan status is on the line %d, in the header", row) + } + if line := strings.TrimRight(ansi.Strip(lines[row]), " "); !strings.HasSuffix(line, "│") || ansi.StringWidth(line) != normalizeViewWidth(m.width) { + t.Errorf("the scan box is not at the right edge: %q", line) + } +} + +// TestScanBoxDoesNotCoverChapterOverlay verifies that the chapter overlay +// covers the box of a running scan, and not the reverse. +func TestScanBoxDoesNotCoverChapterOverlay(t *testing.T) { + m := newPlaybackTestModel() + m.width = 100 + m.height = 30 + m.sessionID = "sess-123" + m.player.Title = "Test Book" + m.player.Playing = true + for i := 0; i < 25; i++ { + m.chapters = append(m.chapters, abs.Chapter{ID: i, Start: float64(i * 60), End: float64(i*60 + 60), Title: fmt.Sprintf("Chapter %d", i+1)}) + } + m.chapterOverlayVisible = true + + // The footer covers the last lines of a high overlay, also with no scan. + noScan := ansi.Strip(m.View()) + m.scanStatus = "Scanning Audiobooks…" + view := ansi.Strip(m.View()) + for _, line := range strings.Split(ansi.Strip(m.viewChapterOverlay()), "\n") { + if strings.Contains(noScan, line) && !strings.Contains(view, line) { + t.Fatalf("the scan box covers the line %q of the chapter overlay", line) + } + } +} + +// TestScanBoxDoesNotCoverErrorBanner verifies that the box of a running scan +// is below the error banner, so that the end of a long error stays visible. +func TestScanBoxDoesNotCoverErrorBanner(t *testing.T) { + m := newTestModelAuthenticated() + result, _ := m.Update(tea.WindowSizeMsg{Width: 100, Height: 30}) + m = result.(Model) + m.scanStatus = "Scanning Audiobooks…" + _ = m.err.SetError(errors.New(strings.Repeat("long error ", 20))) + m.propagateSize() + + banner := "" + for _, line := range strings.Split(ansi.Strip(m.View()), "\n") { + if strings.Contains(line, "⚠") { + banner = line + } + } + if banner == "" { + t.Fatal("the view shows no error banner") + } + if strings.ContainsAny(banner, "╭│╰") { + t.Errorf("the scan box covers the error banner: %q", banner) + } +} diff --git a/internal/app/sessions.go b/internal/app/sessions.go index 8b8561d..12e6965 100644 --- a/internal/app/sessions.go +++ b/internal/app/sessions.go @@ -26,7 +26,7 @@ func (m Model) handleSessionsKey() (Model, tea.Cmd) { } return m.openSessions(sessionsTarget(item, episode)) case m.isPlaying(): - return m.openSessions(sessions.Target{ItemID: m.itemID, EpisodeID: m.episodeID, Title: m.player.Title}) + return m.openSessions(sessions.Target{ItemID: m.itemID, EpisodeID: m.episodeID, Title: m.player.Title, LibraryID: m.playbackLibraryID}) } return m.openSessions(sessions.Target{}) } @@ -44,9 +44,9 @@ func (m Model) openSessions(target sessions.Target) (Model, tea.Cmd) { func sessionsTarget(item abs.LibraryItem, episode *abs.PodcastEpisode) sessions.Target { if episode != nil { - return sessions.Target{ItemID: item.ID, EpisodeID: episode.ID, Title: episode.Title} + return sessions.Target{ItemID: item.ID, EpisodeID: episode.ID, Title: episode.Title, LibraryID: item.LibraryID} } - return sessions.Target{ItemID: item.ID, Title: item.Media.Metadata.Title} + return sessions.Target{ItemID: item.ID, Title: item.Media.Metadata.Title, LibraryID: item.LibraryID} } // handlePlayFromSession leaves the sessions screen and plays the item of a diff --git a/internal/app/sessions_test.go b/internal/app/sessions_test.go index 843fc92..a3f411e 100644 --- a/internal/app/sessions_test.go +++ b/internal/app/sessions_test.go @@ -181,3 +181,25 @@ func TestPaletteListeningSessionsOfDetailTarget(t *testing.T) { _, _ = feedCmd(m, cmd) assertAPICallMade(t, log, "GET", "/api/me/item/listening-sessions/pod-001/pod-001-ep-001") } + +// TestSessionsTargetHasLibraryOfItem verifies that the sessions of an item +// keep the library of the item, so that the palette of the sessions screen +// uses that library and not the library of the home screen. +func TestSessionsTargetHasLibraryOfItem(t *testing.T) { + item := abs.LibraryItem{ID: "b-1", LibraryID: "lib-b"} + if got := sessionsTarget(item, nil).LibraryID; got != "lib-b" { + t.Errorf("library of a book target = %q, want lib-b", got) + } + if got := sessionsTarget(item, &abs.PodcastEpisode{ID: "ep-1"}).LibraryID; got != "lib-b" { + t.Errorf("library of an episode target = %q, want lib-b", got) + } + + m := newTestModelAuthenticated() + m.sessionID = "sess-1" + m.itemID = "b-1" + m.playbackLibraryID = "lib-b" + m, _ = m.handleSessionsKey() + if got := m.sessions.LibraryID(); got != "lib-b" { + t.Errorf("library of the item that plays = %q, want lib-b", got) + } +} diff --git a/internal/cache/client.go b/internal/cache/client.go index 138271b..f1a6876 100644 --- a/internal/cache/client.go +++ b/internal/cache/client.go @@ -26,9 +26,9 @@ type Client struct { store *Store OnInvalidate func() - // generation counts the calls of invalidate. cached does not store the + // 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 + // 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 @@ -155,10 +155,10 @@ func (c *Client) GetBookmarks(ctx context.Context, itemID string) ([]abs.Bookmar }) } -// invalidate wipes the persistent cache after a change on the server, and +// Invalidate wipes the persistent cache after a change on the server, and // 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() { +func (c *Client) Invalidate() { if c.store != nil { c.mu.Lock() c.generation++ @@ -178,7 +178,7 @@ func (c *Client) ScanLibrary(ctx context.Context, libraryID string) error { if err := c.Client.ScanLibrary(ctx, libraryID); err != nil { return err } - c.invalidate() + c.Invalidate() return nil } @@ -187,7 +187,7 @@ func (c *Client) DeleteItem(ctx context.Context, itemID string, hardDelete bool) if err := c.Client.DeleteItem(ctx, itemID, hardDelete); err != nil { return err } - c.invalidate() + c.Invalidate() return nil } @@ -196,7 +196,7 @@ func (c *Client) DeleteEpisode(ctx context.Context, podcastID string, episodeID if err := c.Client.DeleteEpisode(ctx, podcastID, episodeID, hardDelete); err != nil { return err } - c.invalidate() + c.Invalidate() return nil } @@ -206,7 +206,7 @@ func (c *Client) UpdateLibraryItemMedia(ctx context.Context, itemID string, req if err != nil { return nil, err } - c.invalidate() + c.Invalidate() return updated, nil } @@ -216,6 +216,6 @@ func (c *Client) UpdatePodcastEpisode(ctx context.Context, itemID, episodeID str if err != nil { return nil, err } - c.invalidate() + c.Invalidate() return updated, nil } diff --git a/internal/cache/store.go b/internal/cache/store.go index e43a3eb..72e4bdb 100644 --- a/internal/cache/store.go +++ b/internal/cache/store.go @@ -14,7 +14,7 @@ import ( // keyVersion is the prefix of each key in the database. Raise it when the // type of a cached value changes: the store then does not read the old rows, // and EvictExpired deletes them when they expire. -const keyVersion = "v1-" +const keyVersion = "v2-" // Store provides generic get/put/delete/evict operations over a SQLite table. type Store struct { diff --git a/internal/cache/store_test.go b/internal/cache/store_test.go index 3414bcd..c5ae926 100644 --- a/internal/cache/store_test.go +++ b/internal/cache/store_test.go @@ -92,14 +92,14 @@ func TestStore_KeysHaveVersion(t *testing.T) { if err := s.Put("k", "value", time.Minute); err != nil { t.Fatalf("Put error: %v", err) } - if n := rows("v1-k"); n != 1 { - t.Fatalf("rows with key v1-k = %d, want 1", n) + if n := rows("v2-k"); n != 1 { + t.Fatalf("rows with key v2-k = %d, want 1", n) } if err := s.Delete("k"); err != nil { t.Fatalf("Delete error: %v", err) } - if n := rows("v1-k"); n != 0 { - t.Fatalf("rows with key v1-k after Delete = %d, want 0", n) + if n := rows("v2-k"); n != 0 { + t.Fatalf("rows with key v2-k after Delete = %d, want 0", n) } // A row of an older pine, with no version and data that does not decode. diff --git a/internal/screens/detail/model.go b/internal/screens/detail/model.go index 36a9315..5083b96 100644 --- a/internal/screens/detail/model.go +++ b/internal/screens/detail/model.go @@ -232,6 +232,7 @@ type Model struct { bookmarkEditErr string bookmarkInput textinput.Model episodes []abs.PodcastEpisode + episodesLoaded bool selectedEpisode int focusEpisodes bool // finishedEpisodes holds the result of each mark of an episode on this @@ -351,8 +352,15 @@ func (m Model) ItemID() string { return m.item.ID } -// SetEpisodes updates the episode list and refreshes the viewport content. +// SetEpisodes updates the episode list and refreshes the viewport content. The +// first load selects the recent episode. A later load keeps the selected +// episode while it is in the list. func (m *Model) SetEpisodes(episodes []abs.PodcastEpisode) { + selectedID := "" + if m.episodesLoaded && m.selectedEpisode < len(m.episodes) { + selectedID = m.episodes[m.selectedEpisode].ID + } + m.episodesLoaded = true slices.SortFunc(episodes, func(a, b abs.PodcastEpisode) int { aIdx, bIdx := 0, 0 if a.Index != nil { @@ -364,13 +372,15 @@ func (m *Model) SetEpisodes(episodes []abs.PodcastEpisode) { return aIdx - bIdx }) m.episodes = episodes - if m.item.RecentEpisode != nil { - for i, episode := range episodes { - if episode.ID == m.item.RecentEpisode.ID { - m.selectedEpisode = i - break - } - } + selected := -1 + if selectedID != "" { + selected = slices.IndexFunc(episodes, func(e abs.PodcastEpisode) bool { return e.ID == selectedID }) + } + if selected < 0 && m.item.RecentEpisode != nil { + selected = slices.IndexFunc(episodes, func(e abs.PodcastEpisode) bool { return e.ID == m.item.RecentEpisode.ID }) + } + if selected >= 0 { + m.selectedEpisode = selected } if m.selectedEpisode >= len(episodes) { m.selectedEpisode = max(0, len(episodes)-1) diff --git a/internal/screens/detail/model_test.go b/internal/screens/detail/model_test.go index 8e2ef08..e6b1fbc 100644 --- a/internal/screens/detail/model_test.go +++ b/internal/screens/detail/model_test.go @@ -1046,6 +1046,39 @@ func TestMarkFinishedEpisodeKeepsResultPerEpisode(t *testing.T) { } } +// TestSetEpisodes_KeepsSelectedEpisodeOnReload verifies that a second load of +// the episodes keeps the episode that the user selected. The recent episode is +// only the selection of the first load. +func TestSetEpisodes_KeepsSelectedEpisodeOnReload(t *testing.T) { + item := abs.LibraryItem{ + ID: "pod-001", + MediaType: "podcast", + RecentEpisode: &abs.PodcastEpisode{ID: "ep-2"}, + } + episodes := func() []abs.PodcastEpisode { + return []abs.PodcastEpisode{ + {ID: "ep-1", Title: "Episode One"}, + {ID: "ep-2", Title: "Episode Two"}, + {ID: "ep-3", Title: "Episode Three"}, + } + } + + m := New(ui.DefaultStyles(), item) + m.SetEpisodes(episodes()) + m.selectedEpisode = 2 + + m.SetEpisodes(episodes()) + if m.SelectedEpisode() != 2 { + t.Errorf("selected episode after a reload = %d, want 2", m.SelectedEpisode()) + } + + // The selected episode is not in the new list: the recent episode. + m.SetEpisodes(episodes()[:2]) + if m.SelectedEpisode() != 1 { + t.Errorf("selected episode after its removal = %d, want 1", m.SelectedEpisode()) + } +} + func TestSetEpisodes_PreservesRecentEpisodeSelection(t *testing.T) { styles := ui.DefaultStyles() item := abs.LibraryItem{ diff --git a/internal/screens/home/model.go b/internal/screens/home/model.go index e2d5223..e491527 100644 --- a/internal/screens/home/model.go +++ b/internal/screens/home/model.go @@ -3,6 +3,7 @@ package home import ( "context" "fmt" + "slices" "strings" "time" @@ -27,6 +28,13 @@ type PersonalizedMsg struct { Libraries []abs.Library LibraryID string Err error + + // generation is the loadingGen of the load. The screen drops the answer + // of an earlier load. + generation uint64 + // refreshed is true when the load read the library list again. Libraries + // is then the new list, and LibraryID is the library to select in it. + refreshed bool } type rowKind int @@ -197,15 +205,20 @@ func (m *Model) SetSize(width, height int) { // Init returns the initial command that fetches personalized data. func (m Model) Init() tea.Cmd { - return tea.Batch(m.fetchPersonalizedCmd(), m.loadingRevealCmd()) + return tea.Batch(m.fetchPersonalizedCmd(false), m.loadingRevealCmd()) } // Update handles messages for the home screen. func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { switch msg := msg.(type) { case PersonalizedMsg: + if msg.generation != m.loadingGen { + logger.Debug("STALE: discarding personalized msg of an earlier load", "msgLib", msg.LibraryID) + return m, nil + } currentLib := m.SelectedLibraryID() - if msg.LibraryID != "" && currentLib != "" && msg.LibraryID != currentLib { + // The answer of a refresh selects its library in the new library list. + if !msg.refreshed && msg.LibraryID != "" && currentLib != "" && msg.LibraryID != currentLib { logger.Debug("STALE: discarding personalized msg", "msgLib", msg.LibraryID, "currentLib", currentLib) return m, nil } @@ -219,7 +232,10 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { return m, nil } m.err = nil - if len(msg.Libraries) > 0 { + if msg.refreshed { + m.libraries = msg.Libraries + m.selectedLibrary = max(0, slices.IndexFunc(m.libraries, func(lib abs.Library) bool { return lib.ID == msg.LibraryID })) + } else if len(msg.Libraries) > 0 { logger.Debug("personalized: updating libraries", "count", len(msg.Libraries)) m.libraries = msg.Libraries } @@ -297,7 +313,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { // Keep current content visible briefly; show skeletons only if // the fetch outlives the reveal delay. m.refreshListRows() - return m, tea.Batch(m.fetchPersonalizedCmd(), m.loadingRevealCmd()) + return m, tea.Batch(m.fetchPersonalizedCmd(false), m.loadingRevealCmd()) } return m, nil case key.Matches(msg, m.keys.PageDown): @@ -324,15 +340,20 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { } // fetchPersonalizedCmd creates a command that fetches personalized shelves. -func (m *Model) fetchPersonalizedCmd() tea.Cmd { +// With refreshLibraries, the command also reads the library list again, and +// it loads the shelves of the selected library by its ID. +func (m *Model) fetchPersonalizedCmd(refreshLibraries bool) tea.Cmd { + msg := PersonalizedMsg{generation: m.loadingGen, refreshed: refreshLibraries} if m.client == nil { - return func() tea.Msg { - return PersonalizedMsg{Err: fmt.Errorf("not authenticated")} - } + msg.Err = fmt.Errorf("not authenticated") + return func() tea.Msg { return msg } } client := m.client selectedIdx := m.selectedLibrary existingLibs := m.libraries + if refreshLibraries { + existingLibs = nil + } currentLibID := m.SelectedLibraryID() return func() tea.Msg { libs := existingLibs @@ -341,47 +362,48 @@ func (m *Model) fetchPersonalizedCmd() tea.Cmd { var err error libs, err = client.GetLibraries(context.Background()) if err != nil { - return PersonalizedMsg{Err: fmt.Errorf("fetch libraries: %w", err)} + msg.Err = fmt.Errorf("fetch libraries: %w", err) + return msg } libs = client.FilterAudioLibraries(context.Background(), libs) } + msg.Libraries = libs if len(libs) == 0 { - return PersonalizedMsg{Items: nil, Libraries: libs, LibraryID: currentLibID} + msg.LibraryID = currentLibID + return msg } idx := selectedIdx + if refreshLibraries { + idx = max(0, slices.IndexFunc(libs, func(lib abs.Library) bool { return lib.ID == currentLibID })) + } if idx >= len(libs) { idx = 0 } + msg.LibraryID = libs[idx].ID sections, err := client.GetPersonalized(context.Background(), libs[idx].ID) if err != nil { - return PersonalizedMsg{Err: fmt.Errorf("fetch personalized: %w", err), Libraries: libs, LibraryID: libs[idx].ID} + msg.Err = fmt.Errorf("fetch personalized: %w", err) + return msg } - var continueListening []abs.LibraryItem - var recentlyAdded []abs.LibraryItem for _, section := range sections { switch section.ID { case "continue-listening": - continueListening = section.Entities + msg.Items = section.Entities case "recently-added": - recentlyAdded = section.Entities + msg.RecentlyAdded = section.Entities } } if libs[idx].MediaType == "podcast" { if eps, err := client.GetRecentEpisodes(context.Background(), libs[idx].ID, recentlyAddedLimit); err == nil { - recentlyAdded = eps + msg.RecentlyAdded = eps } } - return PersonalizedMsg{ - Items: continueListening, - RecentlyAdded: recentlyAdded, - Libraries: libs, - LibraryID: libs[idx].ID, - } + return msg } } @@ -536,11 +558,22 @@ func removeEpisodeFromItems(items []abs.LibraryItem, itemID, episodeID string) ( // ReloadCmd forces a fresh data fetch for the current library. func (m *Model) ReloadCmd() tea.Cmd { + return m.reloadCmd(false) +} + +// RefreshCmd reads the library list from the client again, and loads the +// shelves of the selected library. The library list and the selected library +// stay on the model until the answer comes. +func (m *Model) RefreshCmd() tea.Cmd { + return m.reloadCmd(true) +} + +func (m *Model) reloadCmd(refreshLibraries bool) tea.Cmd { m.loading = true m.loadingVisible = false m.loadingGen++ m.refreshListRows() - return tea.Batch(m.fetchPersonalizedCmd(), m.loadingRevealCmd()) + return tea.Batch(m.fetchPersonalizedCmd(refreshLibraries), m.loadingRevealCmd()) } // Libraries returns the available libraries. diff --git a/internal/screens/home/model_test.go b/internal/screens/home/model_test.go index f8674d7..edd5f5d 100644 --- a/internal/screens/home/model_test.go +++ b/internal/screens/home/model_test.go @@ -837,7 +837,7 @@ func TestFetchPersonalizedPodcastLibraryUsesRecentEpisodes(t *testing.T) { m.libraries = []abs.Library{{ID: "lib-pod", Name: "Podcasts", MediaType: "podcast"}} m.selectedLibrary = 0 - cmd := m.fetchPersonalizedCmd() + cmd := m.fetchPersonalizedCmd(false) msg := cmd() pMsg, ok := msg.(PersonalizedMsg) if !ok { @@ -881,3 +881,93 @@ func TestListItemFilterValue_PodcastEpisode(t *testing.T) { t.Errorf("FilterValue() = %q, want it to contain 'daily news'", fv) } } + +func refreshTestLibraries() []abs.Library { + return []abs.Library{ + {ID: "lib-1", Name: "One", MediaType: "podcast"}, + {ID: "lib-2", Name: "Two", MediaType: "podcast"}, + } +} + +// TestRefreshDropsAnswerOfEarlierLoad verifies that the answer of a load from +// before a refresh does not replace the answer of the refresh. +func TestRefreshDropsAnswerOfEarlierLoad(t *testing.T) { + libs := refreshTestLibraries() + item := func(id string) []abs.LibraryItem { + return []abs.LibraryItem{{ID: id, LibraryID: "lib-1", MediaType: "podcast"}} + } + m := newTestModel() + m, _ = m.Update(PersonalizedMsg{Libraries: libs, LibraryID: "lib-1", Items: item("old")}) + early := PersonalizedMsg{Libraries: libs, LibraryID: "lib-1", Items: item("early"), generation: m.loadingGen} + + _ = m.RefreshCmd() + if got := m.SelectedLibraryID(); got != "lib-1" { + t.Fatalf("selected library during the refresh = %q, want lib-1", got) + } + m, _ = m.Update(PersonalizedMsg{Libraries: libs, LibraryID: "lib-1", Items: item("new"), generation: m.loadingGen, refreshed: true}) + m, _ = m.Update(early) + + if len(m.items) != 1 || m.items[0].ID != "new" { + t.Errorf("items = %+v, want the item of the refresh", m.items) + } +} + +// TestRefreshKeepsSelectedLibraryByID verifies that the answer of a refresh +// selects the same library in the new library list, and the first library +// when the new list does not have it. +func TestRefreshKeepsSelectedLibraryByID(t *testing.T) { + libs := refreshTestLibraries() + m := newTestModel() + m, _ = m.Update(PersonalizedMsg{Libraries: libs, LibraryID: "lib-1"}) + m.selectedLibrary = 1 + + _ = m.RefreshCmd() + newLibs := append([]abs.Library{{ID: "lib-0", Name: "Zero", MediaType: "podcast"}}, libs...) + m, _ = m.Update(PersonalizedMsg{Libraries: newLibs, LibraryID: "lib-2", generation: m.loadingGen, refreshed: true}) + if got := m.SelectedLibraryID(); got != "lib-2" { + t.Errorf("selected library = %q, want lib-2", got) + } + + _ = m.RefreshCmd() + m, _ = m.Update(PersonalizedMsg{Libraries: libs[:1], LibraryID: "lib-1", generation: m.loadingGen, refreshed: true}) + if got := m.SelectedLibraryID(); got != "lib-1" || m.loading { + t.Errorf("selected library = %q, loading = %v, want lib-1 and no load", got, m.loading) + } +} + +// TestRefreshLoadsShelvesOfSelectedLibraryByID verifies that the command of a +// refresh reads the library list again and loads the shelves of the selected +// library, also when its position in the new list is different. +func TestRefreshLoadsShelvesOfSelectedLibraryByID(t *testing.T) { + var shelves []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.URL.Path == "/api/libraries": + _ = json.NewEncoder(w).Encode(map[string]any{ + "libraries": append([]abs.Library{{ID: "lib-0", Name: "Zero", MediaType: "podcast"}}, refreshTestLibraries()...), + }) + case strings.HasSuffix(r.URL.Path, "/personalized"): + shelves = append(shelves, r.URL.Path) + _ = json.NewEncoder(w).Encode([]abs.PersonalizedResponse{}) + default: + _ = json.NewEncoder(w).Encode(map[string]any{"episodes": []any{}}) + } + })) + defer srv.Close() + + m := New(ui.DefaultStyles(), cache.NewClient(abs.NewClient(srv.URL, "tok"), nil)) + m.libraries = refreshTestLibraries() + m.selectedLibrary = 1 + + msg, ok := m.fetchPersonalizedCmd(true)().(PersonalizedMsg) + if !ok { + t.Fatal("the command gives no PersonalizedMsg") + } + if msg.LibraryID != "lib-2" || len(msg.Libraries) != 3 { + t.Errorf("library = %q with %d libraries, want lib-2 with 3 libraries", msg.LibraryID, len(msg.Libraries)) + } + if len(shelves) != 1 || shelves[0] != "/api/libraries/lib-2/personalized" { + t.Errorf("shelves requests = %v, want only lib-2", shelves) + } +} diff --git a/internal/screens/series/model.go b/internal/screens/series/model.go index 3f047a6..fa306ac 100644 --- a/internal/screens/series/model.go +++ b/internal/screens/series/model.go @@ -14,10 +14,12 @@ import ( tea "github.com/charmbracelet/bubbletea" ) -// LoadedMsg carries a loaded series payload. +// LoadedMsg carries a loaded series payload. SeriesID names the series of the +// load, so that the screen drops the answer for a different series. type LoadedMsg struct { Contents abs.SeriesContents Err error + SeriesID string } // NavigateDetailMsg requests opening a book from the series list. @@ -107,6 +109,9 @@ func (m Model) Init() tea.Cmd { func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { switch msg := msg.(type) { case LoadedMsg: + if msg.SeriesID != m.seriesID { + return m, nil + } m.loading = false m.err = msg.Err if msg.Err != nil { @@ -191,23 +196,23 @@ func (m Model) SelectedItemID() string { } func (m Model) fetchSeriesCmd() tea.Cmd { + seriesID := m.seriesID if m.client == nil { return func() tea.Msg { - return LoadedMsg{Err: fmt.Errorf("not authenticated")} + return LoadedMsg{SeriesID: seriesID, Err: fmt.Errorf("not authenticated")} } } client := m.client libraryID := m.libraryID - seriesID := m.seriesID return func() tea.Msg { contents, err := client.GetSeriesContents(context.Background(), libraryID, seriesID) if err != nil { - return LoadedMsg{Err: fmt.Errorf("fetch series: %w", err)} + return LoadedMsg{SeriesID: seriesID, Err: fmt.Errorf("fetch series: %w", err)} } if contents == nil { - return LoadedMsg{Err: fmt.Errorf("series not found")} + return LoadedMsg{SeriesID: seriesID, Err: fmt.Errorf("series not found")} } - return LoadedMsg{Contents: *contents} + return LoadedMsg{SeriesID: seriesID, Contents: *contents} } } diff --git a/internal/screens/series/model_test.go b/internal/screens/series/model_test.go index b571ba5..6229490 100644 --- a/internal/screens/series/model_test.go +++ b/internal/screens/series/model_test.go @@ -99,7 +99,7 @@ func TestNewStartsWithSkeletonRows(t *testing.T) { func TestSeriesLoadedMsgPopulatesListAndSelectsCurrentItem(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: sampleSeriesContents()}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: sampleSeriesContents()}) if m.Loading() { t.Fatal("expected loading to be false after series load") @@ -111,7 +111,7 @@ func TestSeriesLoadedMsgPopulatesListAndSelectsCurrentItem(t *testing.T) { func TestView_ShowsSeriesNameAndBooks(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: sampleSeriesContents()}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: sampleSeriesContents()}) v := m.View() for _, want := range []string{"The Expanse", "Leviathan Wakes", "Caliban's War"} { @@ -126,7 +126,7 @@ func TestViewShowsFinishedMarkerOnlyForFinishedBooks(t *testing.T) { contents.Items[0].UserMediaProgress = &abs.UserMediaProgress{Progress: 1.0, IsFinished: true} m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: contents}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: contents}) v := m.View() if !strings.Contains(v, "✓ Leviathan Wakes") { @@ -155,7 +155,7 @@ func TestLoadingSkeletonsDoNotRenderSelectedHighlight(t *testing.T) { func TestEnterKey_NavigatesToSelectedBook(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: sampleSeriesContents()}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: sampleSeriesContents()}) _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) if cmd == nil { @@ -173,7 +173,7 @@ func TestEnterKey_NavigatesToSelectedBook(t *testing.T) { func TestHLPageAcrossSeries(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: sampleLongSeriesContents(30)}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: sampleLongSeriesContents(30)}) before := m.list.GlobalIndex() m, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'L'}}) @@ -190,7 +190,7 @@ func TestHLPageAcrossSeries(t *testing.T) { func TestHLFallsBackToExtremes(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Contents: sampleLongSeriesContents(30)}) + m, _ = m.Update(LoadedMsg{SeriesID: "series-expanse", Contents: sampleLongSeriesContents(30)}) for i := 0; i < 5; i++ { m, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'L'}}) @@ -206,3 +206,13 @@ func TestHLFallsBackToExtremes(t *testing.T) { t.Fatalf("H at start should jump to first row: got %d want 0", got) } } + +// TestLoadedMsgOfOtherSeriesIsDropped verifies that the screen drops the +// answer of a load for a different series. +func TestLoadedMsgOfOtherSeriesIsDropped(t *testing.T) { + m := newTestModel() + m, _ = m.Update(LoadedMsg{SeriesID: "series-dune", Contents: sampleSeriesContents()}) + if len(m.series.Items) != 0 || !m.Loading() { + t.Errorf("the screen shows %d books of a different series", len(m.series.Items)) + } +} diff --git a/internal/screens/serieslist/model.go b/internal/screens/serieslist/model.go index ec19f47..80cfcf0 100644 --- a/internal/screens/serieslist/model.go +++ b/internal/screens/serieslist/model.go @@ -19,12 +19,16 @@ const pageLimit = 50 // thresholdPercent is the fraction of loaded items at which a prefetch fires. const thresholdPercent = 0.8 -// LoadedMsg carries a loaded page of series. +// LoadedMsg carries a loaded page of series. LibraryID and Generation name the +// load, so that the screen drops the answer of an earlier load and the answer +// for a different library. type LoadedMsg struct { - Results []abs.Series - Total int - Page int - Err error + Results []abs.Series + Total int + Page int + Err error + LibraryID string + Generation int } // NavigateSeriesMsg requests opening a specific series detail view. @@ -70,6 +74,7 @@ type Model struct { page int total int loading bool + generation int err error } @@ -109,10 +114,21 @@ func (m Model) Init() tea.Cmd { return m.fetchSeriesCmd(0) } +// ReloadCmd loads the first page again. The rows stay until that page comes. +// The screen drops the answer of each load that started before the reload, +// and it starts no load of a next page during the reload. +func (m *Model) ReloadCmd() tea.Cmd { + m.generation++ + return m.fetchSeriesCmd(0) +} + // Update handles messages for the series browser. func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { switch msg := msg.(type) { case LoadedMsg: + if msg.LibraryID != m.libraryID || msg.Generation != m.generation { + return m, nil + } m.loading = false if msg.Err != nil { m.err = msg.Err @@ -193,23 +209,23 @@ func (m *Model) maybePrefetch() tea.Cmd { } func (m *Model) fetchSeriesCmd(page int) tea.Cmd { + msg := LoadedMsg{LibraryID: m.libraryID, Generation: m.generation} if m.client == nil { - return func() tea.Msg { - return LoadedMsg{Err: fmt.Errorf("not authenticated")} - } + msg.Err = fmt.Errorf("not authenticated") + return func() tea.Msg { return msg } } m.loading = true client := m.client - libraryID := m.libraryID return func() tea.Msg { - resp, err := client.GetLibrarySeries(context.Background(), libraryID, page, pageLimit) + resp, err := client.GetLibrarySeries(context.Background(), msg.LibraryID, page, pageLimit) if err != nil { - return LoadedMsg{Err: fmt.Errorf("fetch series: %w", err)} + msg.Err = fmt.Errorf("fetch series: %w", err) + return msg } - if resp == nil { - return LoadedMsg{} + if resp != nil { + msg.Results, msg.Total, msg.Page = resp.Results, resp.Total, resp.Page } - return LoadedMsg{Results: resp.Results, Total: resp.Total, Page: resp.Page} + return msg } } @@ -230,10 +246,14 @@ func (i seriesListItem) Title() string { } func (i seriesListItem) Description() string { + books := fmt.Sprintf("%d books", len(i.series.Books)) + if len(i.series.Books) == 1 { + books = "1 book" + } if strings.TrimSpace(i.series.Description) != "" { - return i.series.Description + return books + " · " + i.series.Description } - return "Series" + return books } func (i seriesListItem) FilterValue() string { diff --git a/internal/screens/serieslist/model_test.go b/internal/screens/serieslist/model_test.go index 23dc91f..31e92cd 100644 --- a/internal/screens/serieslist/model_test.go +++ b/internal/screens/serieslist/model_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/Thelost77/pine/internal/abs" + "github.com/Thelost77/pine/internal/cache" "github.com/Thelost77/pine/internal/ui" tea "github.com/charmbracelet/bubbletea" ) @@ -26,7 +27,7 @@ func sampleSeries() []abs.Series { func TestLoadedMsgPopulatesList(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Results: sampleSeries(), Total: 2, Page: 0}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Results: sampleSeries(), Total: 2, Page: 0}) if m.Loading() { t.Fatal("expected loading to be false after load") @@ -38,9 +39,9 @@ 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}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Results: sampleSeries(), Total: 4, Page: 0}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Err: errors.New("network error")}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", 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) @@ -52,7 +53,7 @@ func TestLoadedMsgClearsEarlierError(t *testing.T) { func TestViewShowsSeriesNames(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Results: sampleSeries(), Total: 2, Page: 0}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Results: sampleSeries(), Total: 2, Page: 0}) v := m.View() for _, want := range []string{"Series", "The Expanse", "Dune"} { @@ -64,7 +65,7 @@ func TestViewShowsSeriesNames(t *testing.T) { func TestEnterNavigatesToSeries(t *testing.T) { m := newTestModel() - m, _ = m.Update(LoadedMsg{Results: sampleSeries(), Total: 2, Page: 0}) + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Results: sampleSeries(), Total: 2, Page: 0}) _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) if cmd == nil { @@ -82,3 +83,68 @@ func TestEnterNavigatesToSeries(t *testing.T) { t.Fatalf("series ID = %q, want series-expanse", navMsg.SeriesID) } } + +// TestViewShowsNumberOfBooks verifies that a row shows the number of books of +// the series, and the description after it. +func TestViewShowsNumberOfBooks(t *testing.T) { + m := newTestModel() + m, _ = m.Update(LoadedMsg{LibraryID: "lib-books-001", Results: []abs.Series{ + {ID: "series-dune", Name: "Dune", Books: []abs.SeriesBook{{ID: "b1"}, {ID: "b2"}}}, + {ID: "series-expanse", Name: "The Expanse", Description: "Space opera", Books: []abs.SeriesBook{{ID: "b3"}}}, + }, Total: 2, Page: 0}) + + v := m.View() + for _, want := range []string{"2 books", "1 book · Space opera"} { + if !strings.Contains(v, want) { + t.Errorf("expected view to contain %q\n%s", want, v) + } + } +} + +func seriesNames(m Model) string { + names := make([]string, len(m.series)) + for i, s := range m.series { + names[i] = s.Name + } + return strings.Join(names, ",") +} + +// TestReloadDropsAnswerOfEarlierLoad verifies that a reload replaces the list +// with the new first page. The answer of a load of a next page that started +// before the reload must not add an old page to the new list. +func TestReloadDropsAnswerOfEarlierLoad(t *testing.T) { + const lib = "lib-books-001" + m := New(ui.DefaultStyles(), cache.NewClient(abs.NewClient("http://test", "tok"), nil), lib, "Books") + m.SetSize(80, 24) + page := func(names ...string) []abs.Series { + series := make([]abs.Series, len(names)) + for i, name := range names { + series[i] = abs.Series{ID: "series-" + name, Name: name} + } + return series + } + m, _ = m.Update(LoadedMsg{LibraryID: lib, Results: page("A", "B"), Total: 6, Page: 0}) + m, _ = m.Update(LoadedMsg{LibraryID: lib, Results: page("C", "D"), Total: 6, Page: 1}) + late := LoadedMsg{LibraryID: lib, Results: page("E", "F"), Total: 6, Page: 2} + + _ = m.ReloadCmd() + if !m.Loading() { + t.Error("the list does not load during a reload, so it can start a load of a next page") + } + m, _ = m.Update(LoadedMsg{LibraryID: lib, Generation: m.generation, Results: page("A", "B2"), Total: 6, Page: 0}) + m, _ = m.Update(late) + + if got := seriesNames(m); got != "A,B2" { + t.Errorf("series = %s, want A,B2", got) + } +} + +// TestLoadedMsgOfOtherLibraryIsDropped verifies that the list drops the answer +// of a load for a different library. +func TestLoadedMsgOfOtherLibraryIsDropped(t *testing.T) { + m := newTestModel() + m, _ = m.Update(LoadedMsg{LibraryID: "lib-other", Results: sampleSeries(), Total: 2, Page: 0}) + if got := seriesNames(m); got != "" { + t.Errorf("series = %s, want none", got) + } +} diff --git a/internal/screens/sessions/model.go b/internal/screens/sessions/model.go index 224c196..f2e6597 100644 --- a/internal/screens/sessions/model.go +++ b/internal/screens/sessions/model.go @@ -19,11 +19,13 @@ import ( const pageSize = 50 // Target is the book or the podcast episode whose sessions the screen shows. -// The zero Target shows the sessions of all items. +// The zero Target shows the sessions of all items. LibraryID is the library of +// the item. type Target struct { ItemID string EpisodeID string Title string + LibraryID string } // LoadedMsg carries the sessions of a target. @@ -191,6 +193,12 @@ func (m *Model) SetSize(width, height int) { } // IsFiltering reports whether the filter input is active. +// LibraryID returns the library of the target item. It is empty for the +// sessions of all items. +func (m Model) LibraryID() string { + return m.target.LibraryID +} + func (m Model) IsFiltering() bool { return m.list.FilterState() == list.Filtering } diff --git a/internal/ui/components/palette.go b/internal/ui/components/palette.go index 5d98c66..2e104f9 100644 --- a/internal/ui/components/palette.go +++ b/internal/ui/components/palette.go @@ -66,6 +66,7 @@ const ( ActionToggleCaptions ActionShowSessions ActionScanLibrary + ActionRefresh ) type PaletteItem struct { @@ -215,11 +216,23 @@ func (p *Palette) Close() { // 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. +// The selected item stays selected while it is in the list. func (p *Palette) Refresh() { if !p.visible || strings.TrimSpace(p.input.Value()) == "" { return } + sel, hadSelection := p.list.SelectedItem().(PaletteItem) p.applyFilter(p.input.Value()) + if !hadSelection || sel.IsHeader { + return + } + for i, item := range p.list.Items() { + pi, ok := item.(PaletteItem) + if ok && !pi.IsHeader && pi.Action == sel.Action && pi.ItemID == sel.ItemID && pi.LibraryID == sel.LibraryID && pi.Label == sel.Label { + p.list.Select(i) + return + } + } } func (p *Palette) Visible() bool { diff --git a/internal/ui/components/palette_test.go b/internal/ui/components/palette_test.go index 5da8293..ce7fc16 100644 --- a/internal/ui/components/palette_test.go +++ b/internal/ui/components/palette_test.go @@ -217,6 +217,40 @@ func TestPaletteSearchFunctionCalled(t *testing.T) { } } +// TestPaletteRefreshKeepsTheSelectedItem verifies that Refresh keeps the +// selected item while it is in the list, and selects the first item when it is +// not. Results that come later then do not move the selection. +func TestPaletteRefreshKeepsTheSelectedItem(t *testing.T) { + p := NewPalette() + results := []PaletteItem{ + {Label: "Dune", Action: ActionContentNavigate, ItemID: "dune-1"}, + {Label: "Dune Messiah", Action: ActionContentNavigate, ItemID: "dune-2"}, + } + p.Open(nil, func(string) []PaletteItem { return results }) + p.input.SetValue("dune") + p.applyFilter("dune") + for i, item := range p.list.Items() { + if pi, ok := item.(PaletteItem); ok && pi.ItemID == "dune-2" { + p.list.Select(i) + } + } + + results = append(results, + PaletteItem{Label: "Podcasts", IsHeader: true}, + PaletteItem{Label: "Dune Talk", Action: ActionContentNavigate, ItemID: "pod-1"}, + ) + p.Refresh() + if sel, _ := p.list.SelectedItem().(PaletteItem); sel.ItemID != "dune-2" { + t.Errorf("selected item = %q, want dune-2", sel.ItemID) + } + + results = []PaletteItem{{Label: "Dune Talk", Action: ActionContentNavigate, ItemID: "pod-1"}} + p.Refresh() + if sel, _ := p.list.SelectedItem().(PaletteItem); sel.ItemID != "pod-1" { + t.Errorf("selected item = %q, want pod-1", sel.ItemID) + } +} + func TestPaletteViewWhenNotVisible(t *testing.T) { p := NewPalette() if v := p.View(); v != "" {