Skip to content
16 changes: 12 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ go vet ./... # type-check
| Packages | Owner |
|----------|-------|
| `internal/logger`, `internal/ui`, `internal/ui/components`, `internal/mpris`, `internal/player` | Shared by pine and spruce |
| `internal/abs`, `internal/app`, `internal/cache`, `internal/captions`, `internal/config`, `internal/db`, `internal/screens` | pine |
| `internal/abs`, `internal/app`, `internal/cache`, `internal/captions`, `internal/config`, `internal/db`, `internal/screens`, `internal/systemsleep` | pine |
| `internal/spruce/app`, `internal/spruce/buildinfo`, `internal/spruce/config`, `internal/spruce/jellyfin`, `internal/spruce/screens` | spruce |

Rules:
Expand Down Expand Up @@ -82,7 +82,7 @@ The Architecture Map below describes pine and the shared packages.
| Screen | Key files | Notes |
|--------|-----------|-------|
| `login` | model.go, view.go | 3-field form (server, username, password), tab navigation |
| `home` | model.go, view.go | Personalized shelves: continue-listening + recently-added. Library switching with tab. Item/recent caches per library. Skeleton loading with 500ms reveal delay. |
| `home` | model.go, view.go | Personalized shelves: continue-listening + recently-added. Library switching with tab. Item/recent caches per library. Skeleton loading with 500ms reveal delay. At start and on a tab switch, `fetchPersonalizedCmd(false, true)` reads only the local cache, expired entries included, and the answer has `cached`. The answer of the server for the same load replaces it. A cached answer applies until the server answers the load with no error (`serverAnswered`), so it also applies after a fast error of the server. A load that reads the library list, at the start or with `RefreshCmd`, has `refreshed`: its answer replaces the list and selects the library by its ID, so the list of the server replaces an old cached list. A failed load keeps the shown shelves of the selected library and goes to the log. A 401 opens the login screen: the root model checks `PersonalizedMsg.Err` with `checkUnauthorized` before the home screen gets the message. |
| `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. |
Expand All @@ -95,9 +95,9 @@ The Architecture Map below describes pine and the shared packages.

| 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(ctx, c, key, ttl, fetch)`, which returns the data of the server. With a `CachedOnly(ctx)` context, `cached` answers from the cache, also from an expired entry, sends no request, and returns `ErrNotCached` if the cache has no entry. 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` (`v2-`). 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. `Get` misses an expired entry. `GetStale` reads an entry until `keepExpired` (30 days) after it expires, and `EvictExpired` deletes it after that time. `Expire` makes a fresh entry expired now. A stop expires the home shelves of the library with it (`evictProgressCaches`), so that the next start can show them from the cache. |

### MPRIS (internal/mpris/, shared)

Expand All @@ -110,6 +110,12 @@ The Architecture Map below describes pine and the shared packages.

The server is written from the MPRIS 2.2 specification. The Go MPRIS server library that exists is GPL-3.0, and a GPL module makes the release binaries GPL. Do not add a module with a copyleft license.

### System sleep (internal/systemsleep/)

`Start(who, prepare)` connects to the system bus and holds a logind sleep delay inhibitor. On `PrepareForSleep(true)`, it calls `prepare(release)` in a goroutine, and it releases the inhibitor when `prepare` calls `release`, or after 10 s, the timeout of an `abs.Client` request. After the wake, it takes a new inhibitor. It waits at most 3 s (`inhibitTimeout`) for an answer to `Inhibit`, and without an answer it runs with no inhibitor. Without a system bus (macOS, Windows), `Start` logs the cause and returns nil, and a nil `Monitor` is valid. The name keeps the package apart from the sleep timer.

`main.go` sends `SystemSleepMsg` to the program. `handleSystemSleep` in `playback.go` stops the playback with `stopPlayback` and calls `Release` after the stop commands in a `tea.Sequence`. pine does not play on after the wake, and the next play takes the position of the server. A start or a change of the track can be in progress with no session yet: `handleSystemSleep` raises `sleepEpoch`, each command that asks for a play session stamps the `PlaySessionMsg` with the epoch of its creation, and `Update` closes a session of an earlier epoch with `closeRestoredSessionCmd` and does not play it. A change of the track (`restartPlaybackAt`) keeps `itemID` with no session, so `handleSystemSleep` also stops then, and quits mpv. NetworkManager can take the network down before the requests end, so the position since the last sync can be lost.

### API (internal/abs/)

| File | Responsibility |
Expand Down Expand Up @@ -174,6 +180,8 @@ Styles from theme config. Format helpers (timestamps, durations). `RunProgram` r
- `internal/mpris/mpris_test.go` for `RootAdapter` and the server properties, and `bridge_test.go` for the bridge
- `internal/mpris/server_linux_test.go` starts the MPRIS server on a private session bus and checks it as an MPRIS client. It skips if `dbus-daemon` is absent. With `PINE_REQUIRE_DBUS=1` it fails instead. CI and `scripts/release.sh` set that variable.
- `internal/app/mpris_linux_test.go` starts the MPRIS server of the pine model on a private session bus and checks the Seeked signals. It skips if `dbus-daemon` is absent. With `PINE_REQUIRE_DBUS=1` it fails instead.
- `internal/systemsleep/systemsleep_linux_test.go` runs a fake logind on a private session bus. Each inhibitor is the write end of a pipe, so the test sees the release as EOF on the read end. It skips if `dbus-daemon` is absent. With `PINE_REQUIRE_DBUS=1` it fails instead.
- `runCmdToEnd` in `internal/app/playback_test.go` runs a command as the Bubble Tea program does, also a `tea.Sequence`. `feedCmd` and `executeBatchCmds` run only batches.
- `internal/screens/metadataedit/model_test.go` for the metadata editor
- Screen models have individual `*_test.go` files
- `internal/player/libmpv_test.go`, `mpv_test.go`, and `group_test.go` play audio through the real libmpv with `ao=null`. They skip if libmpv is absent. With `PINE_REQUIRE_LIBMPV=1` they fail instead. `scripts/release.sh` sets that variable.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ The remaining sections describe pine. For spruce, see [docs/spruce/README.md](do
- In-place filtering (`/`) on home, library, and series lists
- Metadata editor for books and episodes
- MPRIS media-key support on Linux
- Stop of the playback before the system sleeps, on Linux with logind, so that pine is silent after the wake
- Bookmarks — create, edit, navigate to, and delete
- Listening sessions (`R`) — see where each device stopped, and play from that position
- Sleep timer
Expand Down
10 changes: 10 additions & 0 deletions internal/app/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ type PlaySessionMsg struct {
Session PlaySessionData
StreamURL string
AuthToken string
// SleepEpoch is the sleepEpoch of the model when the command asked for
// the session. A session from before a system sleep does not play.
SleepEpoch uint64
}

// PlaySessionData carries the data returned from ABS when starting a session.
Expand Down Expand Up @@ -89,6 +92,13 @@ type SyncTickMsg struct {
Generation uint64
}

// SystemSleepMsg tells that the system prepares to sleep. The model stops the
// playback, and it calls Release when the stop has sent its requests, so
// that logind can continue.
type SystemSleepMsg struct {
Release func()
}

// SessionSyncedMsg carries the result of a sync of the playback session.
// NewSessionID is the session that pine opened because the server did not
// have the session SessionID.
Expand Down
21 changes: 21 additions & 0 deletions internal/app/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ type Model struct {
// of the last session at the start then does nothing.
playRequested bool

// sleepEpoch counts the system sleeps. A command that asks for a play
// session stamps the session with it, and pine closes a session from an
// earlier epoch and does not play it (see PlaySessionMsg.SleepEpoch).
sleepEpoch uint64

// The library and the series of the item that plays: for the cache
// eviction after the playback, and for the series auto-continue.
playbackLibraryID string
Expand Down Expand Up @@ -469,6 +474,13 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, nil

case home.PersonalizedMsg:
// The home screen keeps its shelves on a failed load, so a 401 must
// open the login screen here.
if msg.Err != nil {
if m2, cmd, ok := m.checkUnauthorized(msg.Err); ok {
return m2, cmd
}
}
var cmd tea.Cmd
m.home, cmd = m.home.Update(msg)
cmds := []tea.Cmd{}
Expand Down Expand Up @@ -713,6 +725,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m.handleCaptionLoaded(msg)

case PlaySessionMsg:
if msg.SleepEpoch != m.sleepEpoch {
return m, m.closeSessionFromBeforeSleep(msg.Session)
}
logger.Info("play session started", "session", abs.SessionTag(msg.Session.SessionID), "itemID", msg.Session.ItemID, "episodeID", msg.Session.EpisodeID, "currentTime", msg.Session.CurrentTime, "duration", msg.Session.Duration)
return m.handlePlaySessionMsg(msg)

Expand All @@ -735,6 +750,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, m.startRestorePlaybackCmd(msg)

case RestorePlaySessionMsg:
if msg.PlaySessionMsg.SleepEpoch != m.sleepEpoch {
return m, m.closeSessionFromBeforeSleep(msg.PlaySessionMsg.Session)
}
if m.isPlaying() || m.playRequested {
session := msg.PlaySessionMsg.Session
logger.Info("closing restored session: the user started a playback", "session", abs.SessionTag(session.SessionID), "itemID", session.ItemID)
Expand All @@ -757,6 +775,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
return m, cmd

case SystemSleepMsg:
return m.handleSystemSleep(msg)

case SessionSyncedMsg:
return m.handleSessionSynced(msg), nil

Expand Down
16 changes: 16 additions & 0 deletions internal/app/model_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2817,3 +2817,19 @@ func TestMetadataSavedKeepsDetailProgress(t *testing.T) {
t.Errorf("detail progress = %+v, want the finished progress", got.UserMediaProgress)
}
}

// TestHomeLoadUnauthorizedOpensLogin verifies that a 401 from the load of the
// home shelves opens the login screen, also when the home screen shows
// cached shelves and keeps them on other errors.
func TestHomeLoadUnauthorizedOpensLogin(t *testing.T) {
m := newTestModelAuthenticated()
if m.screen != ScreenHome {
t.Fatalf("screen = %v, want home", m.screen)
}
err := fmt.Errorf("fetch personalized: %w", &abs.HTTPStatusError{StatusCode: http.StatusUnauthorized})

result, _ := m.Update(home.PersonalizedMsg{Err: err})
m = result.(Model)

assertScreen(t, m, ScreenLogin)
}
61 changes: 56 additions & 5 deletions internal/app/playback.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ func (m Model) handlePlayCmd(msg detail.PlayCmd) (Model, tea.Cmd) {

item := msg.Item
client := m.client
sleepEpoch := m.sleepEpoch
startCmd := func() tea.Msg {
device := m.playbackDevice()
session, err := client.StartPlaySession(context.Background(), item.ID, device)
Expand All @@ -189,6 +190,7 @@ func (m Model) handlePlayCmd(msg detail.PlayCmd) (Model, tea.Cmd) {
if err != nil {
return PlaybackErrorMsg{Err: err}
}
playMsg.SleepEpoch = sleepEpoch
return playMsg
}

Expand Down Expand Up @@ -230,6 +232,7 @@ func (m Model) handlePlayEpisodeCmd(msg detail.PlayEpisodeCmd) (Model, tea.Cmd)
item := msg.Item
episode := msg.Episode
client := m.client
sleepEpoch := m.sleepEpoch
startCmd := func() tea.Msg {
device := m.playbackDevice()
session, err := client.StartEpisodePlaySession(context.Background(), item.ID, episode.ID, device)
Expand All @@ -240,6 +243,7 @@ func (m Model) handlePlayEpisodeCmd(msg detail.PlayEpisodeCmd) (Model, tea.Cmd)
if err != nil {
return PlaybackErrorMsg{Err: err}
}
playMsg.SleepEpoch = sleepEpoch
return playMsg
}

Expand Down Expand Up @@ -518,6 +522,7 @@ func (m Model) restartPlaybackAt(bookPos float64) (Model, tea.Cmd) {
m.sessionID = ""
m.timeListened = 0
m.captionCues = nil
sleepEpoch := m.sleepEpoch

return m, func() tea.Msg {
if client != nil && sessionID != "" {
Expand All @@ -537,12 +542,14 @@ func (m Model) restartPlaybackAt(bookPos float64) (Model, tea.Cmd) {
if err != nil {
return PlaybackErrorMsg{Err: err}
}
playMsg.SleepEpoch = sleepEpoch
return playMsg
}
}

func (m Model) startPlaybackAtBookPositionCmd(item abs.LibraryItem, bookPos float64) tea.Cmd {
client := m.client
sleepEpoch := m.sleepEpoch
return func() tea.Msg {
device := m.playbackDevice()
session, err := client.StartPlaySession(context.Background(), item.ID, device)
Expand All @@ -561,6 +568,7 @@ func (m Model) startPlaybackAtBookPositionCmd(item abs.LibraryItem, bookPos floa
if err != nil {
return PlaybackErrorMsg{Err: err}
}
playMsg.SleepEpoch = sleepEpoch
return playMsg
}
}
Expand Down Expand Up @@ -594,6 +602,7 @@ func (m Model) playItemAt(item abs.LibraryItem, episode *abs.PodcastEpisode, pos

func (m Model) startEpisodePlaybackAtPositionCmd(item abs.LibraryItem, episode abs.PodcastEpisode, pos float64) tea.Cmd {
client := m.client
sleepEpoch := m.sleepEpoch
return func() tea.Msg {
device := m.playbackDevice()
session, err := client.StartEpisodePlaySession(context.Background(), item.ID, episode.ID, device)
Expand All @@ -604,6 +613,7 @@ func (m Model) startEpisodePlaybackAtPositionCmd(item abs.LibraryItem, episode a
if err != nil {
return PlaybackErrorMsg{Err: err}
}
playMsg.SleepEpoch = sleepEpoch
return playMsg
}
}
Expand All @@ -626,15 +636,16 @@ func (m Model) startRestorePlaybackCmd(msg RestoreSessionMsg) tea.Cmd {
return m.startRestoredBookPlaybackCmd(*msg.Item)
}

// closeRestoredSessionCmd closes a session that the restore opened and that
// pine does not play. The session has no position to send.
// closeRestoredSessionCmd closes a session that pine opened and does not play:
// a restore that the user superseded, or a session that a command asked for
// before the system slept. The session has no position to send.
func closeRestoredSessionCmd(client *cache.Client, sessionID string) tea.Cmd {
if client == nil || sessionID == "" {
return nil
}
return func() tea.Msg {
if err := client.CloseSessionNoSync(context.Background(), sessionID); err != nil {
logger.Warn("failed to close restored session", "session", abs.SessionTag(sessionID), "err", err)
logger.Warn("failed to close an unused session", "session", abs.SessionTag(sessionID), "err", err)
}
return nil
}
Expand All @@ -643,6 +654,7 @@ func closeRestoredSessionCmd(client *cache.Client, sessionID string) tea.Cmd {
func (m Model) startRestoredBookPlaybackCmd(item abs.LibraryItem) tea.Cmd {
client := m.client
store := m.db
sleepEpoch := m.sleepEpoch
return func() tea.Msg {
device := m.playbackDevice()
session, err := client.StartPlaySession(context.Background(), item.ID, device)
Expand Down Expand Up @@ -681,13 +693,15 @@ func (m Model) startRestoredBookPlaybackCmd(item abs.LibraryItem) tea.Cmd {
logSkippedRestore("book playback session invalid", "itemID", item.ID, "session", abs.SessionTag(session.ID), "err", err)
return nil
}
playMsg.SleepEpoch = sleepEpoch
return RestorePlaySessionMsg{PlaySessionMsg: playMsg}
}
}

func (m Model) startRestoredEpisodePlaybackCmd(item abs.LibraryItem, episode abs.PodcastEpisode) tea.Cmd {
client := m.client
store := m.db
sleepEpoch := m.sleepEpoch
return func() tea.Msg {
device := m.playbackDevice()
session, err := client.StartEpisodePlaySession(context.Background(), item.ID, episode.ID, device)
Expand Down Expand Up @@ -720,6 +734,7 @@ func (m Model) startRestoredEpisodePlaybackCmd(item abs.LibraryItem, episode abs
logSkippedRestore("podcast episode playback session invalid", "itemID", item.ID, "episodeID", episode.ID, "session", abs.SessionTag(session.ID), "err", err)
return nil
}
playMsg.SleepEpoch = sleepEpoch
return RestorePlaySessionMsg{PlaySessionMsg: playMsg}
}
}
Expand Down Expand Up @@ -969,14 +984,16 @@ func (m Model) handleSessionSynced(msg SessionSyncedMsg) Model {
}

// evictProgressCaches drops cached data that embeds user progress for an item:
// the library item, the home shelves, and the series view.
// the library item, the home shelves, and the series view. The home shelves
// only expire, so that the next start can show them from the cache before
// the server answers.
func evictProgressCaches(store *cache.Store, itemID, libraryID, seriesID string) {
if store == nil || itemID == "" {
return
}
_ = store.Delete(cache.ItemKey(itemID))
if libraryID != "" {
_ = store.Delete(cache.PersonalizedKey(libraryID))
_ = store.Expire(cache.PersonalizedKey(libraryID))
}
if seriesID != "" {
_ = store.Delete(cache.SeriesContentsKey(seriesID))
Expand Down Expand Up @@ -1067,6 +1084,40 @@ func (m Model) stopPlayback() (Model, tea.Cmd) {
return m, tea.Batch(closeCmd, stopCmd)
}

// handleSystemSleep stops the playback before the system sleeps, so that it
// does not play on after the wake, and so that a later sync cannot replace
// newer progress of another device. The next play takes the position of the
// server. Release runs after each stop command has ended. A network that is
// already down makes the requests fail, and the position since the last sync
// is then lost.
//
// A start or a change of the track can be in progress with no session yet.
// The new sleep epoch makes pine close the session that such a command gets,
// and a change of the track that keeps the item (restartPlaybackAt) stops
// here, so that mpv does not play on.
func (m Model) handleSystemSleep(msg SystemSleepMsg) (Model, tea.Cmd) {
release := func() tea.Msg {
if msg.Release != nil {
msg.Release()
}
return nil
}
m.sleepEpoch++
if !m.isPlaying() && m.itemID == "" {
return m, release
}
logger.Info("system sleep: stopping playback", "session", abs.SessionTag(m.sessionID), "itemID", m.itemID)
m, stopCmd := m.stopPlayback()
return m, tea.Sequence(stopCmd, release)
}

// closeSessionFromBeforeSleep closes a play session that a command asked for
// before the system slept, and does not play it.
func (m Model) closeSessionFromBeforeSleep(session PlaySessionData) tea.Cmd {
logger.Info("system sleep: closing a play session from before the sleep", "session", abs.SessionTag(session.SessionID), "itemID", session.ItemID, "episodeID", session.EpisodeID)
return closeRestoredSessionCmd(m.client, session.SessionID)
}

// stopPlaybackCmds stops the playback as stopPlayback does. It returns the
// close of the session apart from the other cleanup commands, so that a
// caller can run a play request after the close with closeThen.
Expand Down
Loading