Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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)

Expand All @@ -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}]`) |
Expand Down Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions internal/abs/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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))
}
}
69 changes: 34 additions & 35 deletions internal/abs/libraries.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,14 +214,16 @@ 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.
func (c *Client) GetLibrarySeries(ctx context.Context, libraryID string, page, limit int) (*LibrarySeriesResponse, error) {
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 {
Expand All @@ -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)
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Loading
Loading