5 Commits
Author SHA1 Message Date
nilsandClaude Opus 5.5 d84c566412 Release v0.4.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019reK4DUGYqDUjniWYJvwUW
2026-10-21 16:59:05 +02:00
nilsandClaude Opus 5.5 35278bf2f5 README: screenshots
A library screenshot at the top and a gallery of the other views (search,
releases, episodes, downloads, calendar, config, light theme). They show a
made-up library with generated posters, served by a fake Radarr, Sonarr
and SABnzbd, taken in Ghostty with real-image posters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019reK4DUGYqDUjniWYJvwUW
2026-10-21 16:55:19 +02:00
nilsandClaude Opus 5.5 b5c1f60464 Release v0.4.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019reK4DUGYqDUjniWYJvwUW
2026-10-21 16:28:14 +02:00
nilsandClaude Opus 5.5 2798977867 Real-image posters of library titles: use the 500 px copy
Library titles fetched Radarr's/Sonarr's 250×375 poster copy, which
real images show at up to 640 pixels, so movie posters looked soft next
to series posters that came from the provider's full-size original
(Sonarr behind a login). With real images the 500×750 copy is used;
block-character posters keep the small one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019reK4DUGYqDUjniWYJvwUW
2026-10-21 15:31:56 +02:00
nilsandClaude Opus 5.5 b259e22458 First start: create the config file and open the Config view
Without a config file arr-tui refused to start. It now creates an empty
one (private, with its directory) and opens the Config view. A service
with neither address nor key is "not configured", which validation
allows: its client returns ErrNotConfigured without a request, its
indicator stays grey, it is logged once as information, and its lists
say so instead of showing errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019reK4DUGYqDUjniWYJvwUW
2026-10-21 15:16:08 +02:00
27 changed files with 291 additions and 48 deletions
+19
View File
@@ -1,5 +1,24 @@
# Changelog # Changelog
## v0.4.1
- The README shows screenshots of every view (a made-up library). No changes to the program.
## v0.4.0
New:
- **First start without a config file:** arr-tui creates the file (private, with its directory)
and opens the Config view to enter the services, instead of refusing to start.
- **Services may be left out:** one without address and key is not used (e.g. no SABnzbd); its
indicator stays grey and its lists say "not configured" instead of showing errors.
Fixed:
- Library posters shown as real images (kitty, Ghostty) were soft: they used Radarr's/Sonarr's
250×375 copy, enlarged to up to 640 pixels. Real images now use the 500×750 copy; block-character
posters keep the small one.
## v0.3.0 ## v0.3.0
New: New:
+23 -3
View File
@@ -4,6 +4,8 @@ A terminal UI to search for movies and series with [Radarr](https://radarr.video
[Sonarr](https://sonarr.tv), pick releases by hand, and follow the downloads in [Sonarr](https://sonarr.tv), pick releases by hand, and follow the downloads in
[SABnzbd](https://sabnzbd.org). [SABnzbd](https://sabnzbd.org).
![The library: movies and series with their status, and the details of the selected title with its poster](docs/screenshots/library.png)
- **Movies / Series**: search as you type, add titles with a quality profile and root folder, - **Movies / Series**: search as you type, add titles with a quality profile and root folder,
optionally start the automatic search. optionally start the automatic search.
- **Interactive search**: list the releases Radarr/Sonarr find (approved or rejected, with reasons), - **Interactive search**: list the releases Radarr/Sonarr find (approved or rejected, with reasons),
@@ -46,6 +48,22 @@ A terminal UI to search for movies and series with [Radarr](https://radarr.video
Requires Radarr/Sonarr v3+ API (Radarr 5/6, Sonarr 4) and SABnzbd 4+. Only Usenet releases are Requires Radarr/Sonarr v3+ API (Radarr 5/6, Sonarr 4) and SABnzbd 4+. Only Usenet releases are
shown for grabbing, torrents are hidden. shown for grabbing, torrents are hidden.
## Screenshots
The screenshots show a made-up library (invented titles, generated posters), taken in Ghostty,
where posters are real images.
| | |
|---|---|
| ![Search as you type, with the details and poster of the selected result](docs/screenshots/search.png) | ![Interactive search: the releases the indexers found, approved and rejected, sortable and filterable](docs/screenshots/releases.png) |
| **Movies / Series**: search as you type | **Releases**: pick one by hand |
| ![A series' seasons and episodes, with the poster and the selected season's details](docs/screenshots/episodes.png) | ![Downloads: the SABnzbd queue, the Radarr/Sonarr queues with problems, and the history](docs/screenshots/downloads.png) |
| **Seasons and episodes** of a series | **Downloads** from SABnzbd, Radarr and Sonarr |
| ![Calendar: the next two weeks of releases and episodes, grouped by day](docs/screenshots/calendar.png) | ![Config view: every setting in one list, with defaults loaded from the servers](docs/screenshots/config.png) |
| **Calendar** of the next two weeks | **Config** inside the program |
| ![The library in the light theme](docs/screenshots/library-light.png) | |
| **Light theme** | |
## Install ## Install
```sh ```sh
@@ -56,9 +74,11 @@ or build from a checkout (`make build`), or `make dist` for cross-compiled binar
## Configure ## Configure
Copy `config.example.json` to `$XDG_CONFIG_HOME/arr-tui/config.json` (usually Just start `arr-tui`: on the first start it creates `$XDG_CONFIG_HOME/arr-tui/config.json`
`~/.config/arr-tui/config.json`), or pass `--config path`. API keys are in each app under (usually `~/.config/arr-tui/config.json`, or the file given with `--config path`) and opens the
Settings → General. Config view (F6), where you enter the address and API key of each service and save. API keys are in
each app under Settings → General. A service left empty is not used (e.g. no SABnzbd), its indicator
stays grey. You can also write the file yourself, starting from `config.example.json`:
```json ```json
{ {
+2 -2
View File
@@ -66,10 +66,10 @@ Notes:
- **Posters:** the detail panes show the poster at the top right; the head (title, facts, path) and the plot are one text that flows along the poster's left side and continues at full width below it (text is wrapped by arr-tui itself, with a narrower width for the first lines); on panes too small for the poster, the text simply uses the full width. Two ways to draw the poster, chosen by `ui.cover_style`: - **Posters:** the detail panes show the poster at the top right; the head (title, facts, path) and the plot are one text that flows along the poster's left side and continues at full width below it (text is wrapped by arr-tui itself, with a narrower width for the first lines); on panes too small for the poster, the text simply uses the full width. Two ways to draw the poster, chosen by `ui.cover_style`:
- **Real images** (`kitty`, and `auto` in kitty/Ghostty): the Kitty graphics protocol with Unicode placeholders. The poster (kept up to 640 px tall) is uploaded as PNG (`a=t,f=100,q=2`, 4096-byte base64 chunks) and placed virtually with the cell footprint (`a=p,U=1,c=,r=`) right away. Every footprint (crop and cell size) is its own image id, placed once and never changed: Ghostty kept showing the old, small placement when the size of an existing one was changed, so a new size uploads under a new id and deletes the old one. The poster is shown by writing U+10EEEE placeholder characters whose combining marks give row and column (the 297-entry table from the protocol) and whose foreground color is the image id. Since it is ordinary text, popups, dialogs and view changes cover it correctly and tcell's diffing keeps it in place. The footprint uses the real cell size in pixels (the window's pixel size divided by its cell count, rounded down to whole pixels so padding around the grid does not skew it; all images are deleted whenever the window or cell size changes, block characters stand in while the size keeps changing, and real images are uploaded afresh once it has been stable for 300 ms, because uploading and placing for every intermediate size of a window drag raced with the terminal's own resizing) and a box whose shape is within 3% of the poster's; the remaining sliver is cropped from the poster's edges before upload (one upload per size, the previous one is deleted), because the terminal letterboxes an image that does not fit its box exactly. As a second safeguard the placeholder cells use the panes' background color, so anything the picture does not cover blends in (without it the terminal's own, slightly different, default background showed as grey bars beside the poster). Writes to the terminal go through the screen's tty on the UI goroutine, so they cannot interleave with drawing. Requires 24-bit color; otherwise, and inside tmux/screen, the block fallback is used. Terminals are recognised from `TERM`/`TERM_PROGRAM`/`KITTY_WINDOW_ID`/`GHOSTTY_RESOURCES_DIR`, and then asked before the screen starts (a Kitty graphics query and a background-color query followed by a device-attributes request, 300 ms timeout, waiting with select(2) because a read deadline does not work on a terminal device on macOS): only a terminal that answers the query gets real images, also with `cover_style: kitty`, because a terminal without the protocol prints the commands as text. The Log says which way posters are drawn. With `ARR_TUI_DEBUG_GFX=1` the Log (F7) lists every window size, the cell shape, every upload (poster size, crop, cells) and every change of what is drawn (image id, position, cells); with a path (`ARR_TUI_DEBUG_GFX=/tmp/arr-gfx.log`) the same lines also go to that file with millisecond timestamps, so they can be read without leaving the view that shows the problem. The go-termimg library was looked at and not used: its placeholder support is marked experimental, its diacritic table does not match the protocol's, and it writes images straight to the terminal instead of through the screen. - **Real images** (`kitty`, and `auto` in kitty/Ghostty): the Kitty graphics protocol with Unicode placeholders. The poster (kept up to 640 px tall) is uploaded as PNG (`a=t,f=100,q=2`, 4096-byte base64 chunks) and placed virtually with the cell footprint (`a=p,U=1,c=,r=`) right away. Every footprint (crop and cell size) is its own image id, placed once and never changed: Ghostty kept showing the old, small placement when the size of an existing one was changed, so a new size uploads under a new id and deletes the old one. The poster is shown by writing U+10EEEE placeholder characters whose combining marks give row and column (the 297-entry table from the protocol) and whose foreground color is the image id. Since it is ordinary text, popups, dialogs and view changes cover it correctly and tcell's diffing keeps it in place. The footprint uses the real cell size in pixels (the window's pixel size divided by its cell count, rounded down to whole pixels so padding around the grid does not skew it; all images are deleted whenever the window or cell size changes, block characters stand in while the size keeps changing, and real images are uploaded afresh once it has been stable for 300 ms, because uploading and placing for every intermediate size of a window drag raced with the terminal's own resizing) and a box whose shape is within 3% of the poster's; the remaining sliver is cropped from the poster's edges before upload (one upload per size, the previous one is deleted), because the terminal letterboxes an image that does not fit its box exactly. As a second safeguard the placeholder cells use the panes' background color, so anything the picture does not cover blends in (without it the terminal's own, slightly different, default background showed as grey bars beside the poster). Writes to the terminal go through the screen's tty on the UI goroutine, so they cannot interleave with drawing. Requires 24-bit color; otherwise, and inside tmux/screen, the block fallback is used. Terminals are recognised from `TERM`/`TERM_PROGRAM`/`KITTY_WINDOW_ID`/`GHOSTTY_RESOURCES_DIR`, and then asked before the screen starts (a Kitty graphics query and a background-color query followed by a device-attributes request, 300 ms timeout, waiting with select(2) because a read deadline does not work on a terminal device on macOS): only a terminal that answers the query gets real images, also with `cover_style: kitty`, because a terminal without the protocol prints the commands as text. The Log says which way posters are drawn. With `ARR_TUI_DEBUG_GFX=1` the Log (F7) lists every window size, the cell shape, every upload (poster size, crop, cells) and every change of what is drawn (image id, position, cells); with a path (`ARR_TUI_DEBUG_GFX=/tmp/arr-gfx.log`) the same lines also go to that file with millisecond timestamps, so they can be read without leaving the view that shows the problem. The go-termimg library was looked at and not used: its placeholder support is marked experimental, its diacritic table does not match the protocol's, and it writes images straight to the terminal instead of through the screen.
- **Block characters** (`quadrant`, `sextant`, `cells`, and the fallback): every cell shows several pixels in the best two-color split (`quadrant`: 2×2 pixels, glyphs from the Block Elements range every font has; `sextant`: 2×3 pixels, sharper, glyphs from Symbols for Legacy Computing; `cells`: 1 pixel per cell drawn as background color only, because macOS Terminal draws block elements from the font with the halves off the cell's middle). `auto` picks cells in macOS Terminal (`TERM_PROGRAM=Apple_Terminal`), sextants on kitty, WezTerm, foot and Ghostty, and on other terminals (not on macOS, whose terminals do not use fontconfig's fonts) when fontconfig lists a font with the sextant characters (`fc-list :charset=1fb00`, about 20 ms at startup; terminals draw glyphs their font lacks from fallback fonts; skipped over SSH because the installed fonts are the remote machine's), and quadrants otherwise. - **Block characters** (`quadrant`, `sextant`, `cells`, and the fallback): every cell shows several pixels in the best two-color split (`quadrant`: 2×2 pixels, glyphs from the Block Elements range every font has; `sextant`: 2×3 pixels, sharper, glyphs from Symbols for Legacy Computing; `cells`: 1 pixel per cell drawn as background color only, because macOS Terminal draws block elements from the font with the halves off the cell's middle). `auto` picks cells in macOS Terminal (`TERM_PROGRAM=Apple_Terminal`), sextants on kitty, WezTerm, foot and Ghostty, and on other terminals (not on macOS, whose terminals do not use fontconfig's fonts) when fontconfig lists a font with the sextant characters (`fc-list :charset=1fb00`, about 20 ms at startup; terminals draw glyphs their font lacks from fallback fonts; skipped over SSH because the installed fonts are the remote machine's), and quadrants otherwise.
Posters are JPEG, PNG, GIF or WebP (Radarr and Sonarr keep whatever bytes the provider sent under a `.jpg` name, which can be WebP), decoded and downscaled in the process; for any other format the Log says what the data looked like (e.g. AVIF, an HTML error page, or its first bytes). Library items fetch `/MediaCover/<id>/poster-250.jpg` from their Radarr/Sonarr instance with the API key (then the original `poster.jpg`; an instance that answers 200 with an HTML page, i.e. wants a login for `/MediaCover`, is also tried with the key as the `apikey` query parameter; and if the instance has no usable copy, the provider's `remoteUrl`, fetched without credentials); search results fall back to the provider's `remoteUrl` (fetched without credentials). Posters are cached in memory (the terminal's copies are deleted when the cache is dropped and on exit), failed downloads are not retried for two minutes and are written to the Log (F7) with the reason, and the poster shrinks or disappears when the pane is too short. `ui.covers: false` disables it. Posters are JPEG, PNG, GIF or WebP (Radarr and Sonarr keep whatever bytes the provider sent under a `.jpg` name, which can be WebP), decoded and downscaled in the process; for any other format the Log says what the data looked like (e.g. AVIF, an HTML error page, or its first bytes). Library items fetch `/MediaCover/<id>/poster-250.jpg` (250×375; `poster-500.jpg` when posters are real images, which otherwise enlarge the small copy) from their Radarr/Sonarr instance with the API key (then the original `poster.jpg`; an instance that answers 200 with an HTML page, i.e. wants a login for `/MediaCover`, is also tried with the key as the `apikey` query parameter; and if the instance has no usable copy, the provider's `remoteUrl`, fetched without credentials); search results fall back to the provider's `remoteUrl` (fetched without credentials). Posters are cached in memory (the terminal's copies are deleted when the cache is dropped and on exit), failed downloads are not retried for two minutes and are written to the Log (F7) with the reason, and the poster shrinks or disappears when the pane is too short. `ui.covers: false` disables it.
- **Calendar view (F5):** a two-week window (starting today, moved a week at a time with `[`/`]`, `t` returns to today) with the library's movie releases and airing episodes, grouped by day. Radarr `GET /calendar` supplies the cinema, digital and physical release dates (taken as written: midnight UTC means that calendar day) and Sonarr `GET /calendar?includeSeries=true` the episodes with their air time (shown in local time). Unmonitored items are included with `u`. A movie appears once per release date in the window. Each entry shows type, title, episode or release kind and status (downloaded / missing / upcoming); the detail pane shows poster and plot; `Enter`/`i` starts the release search and `s` an automatic search. - **Calendar view (F5):** a two-week window (starting today, moved a week at a time with `[`/`]`, `t` returns to today) with the library's movie releases and airing episodes, grouped by day. Radarr `GET /calendar` supplies the cinema, digital and physical release dates (taken as written: midnight UTC means that calendar day) and Sonarr `GET /calendar?includeSeries=true` the episodes with their air time (shown in local time). Unmonitored items are included with `u`. A movie appears once per release date in the window. Each entry shows type, title, episode or release kind and status (downloaded / missing / upcoming); the detail pane shows poster and plot; `Enter`/`i` starts the release search and `s` an automatic search.
- **Download notifications:** a background poller (independent of the visible view) reads SABnzbd's history every 15 s and announces downloads that reach `Completed` or `Failed` as a popup and log entry; the first poll only records the current state. `ui.notify_downloads` (default true) and `ui.bell` (default false, rings the terminal bell) control it. Connection errors are not reported here, the indicators and the log already do that. - **Download notifications:** a background poller (independent of the visible view) reads SABnzbd's history every 15 s and announces downloads that reach `Completed` or `Failed` as a popup and log entry; the first poll only records the current state. `ui.notify_downloads` (default true) and `ui.bell` (default false, rings the terminal bell) control it. Connection errors are not reported here, the indicators and the log already do that.
- **Config view (F6):** one list with a field for every setting of the config file, one below the other under the headings Radarr, Sonarr, SABnzbd and Interface (a single scrolling form; ↑↓ passes over the headings and ↓ after the last field reaches the Save / Revert buttons, so no Tab is needed; Tab jumps between the fields and the buttons). The `Test` button is part of the list, right below the SABnzbd settings; `Save` and `Revert` are centered in a bar below the list. The fields start from the settings in use; API keys are masked (a checkbox shows them). The default quality profile and root folder of Radarr and Sonarr are dropdowns filled from the server (`/qualityprofile`, `/rootfolder`) with the address and key currently in the fields: when the view opens, on Revert, and 700 ms after the address or key was last changed; answers for values that have changed since are dropped, a failure is reported once in the result box. "(none)" comes first; a configured value the server does not list stays as an option, marked "(not on the server)", so opening the view never changes a setting. `Test` builds temporary clients from the typed values and reports each service. `Save` validates like startup does (URLs, non-empty keys, refresh 1–3600 s), then writes the file from the file's own contents plus the edits (`config.LoadFile`), so values that only come from `ARR_TUI_*` environment variables are left as the file has them and are shown greyed out; the write is atomic (temp file + rename) and keeps the file's permissions (`0600` when new); defaults such as `covers: true` stay out of the file unless it already named them. Everything then applies without a restart: the Radarr/Sonarr/SABnzbd clients are re-pointed (`Reconfigure`, guarded by a mutex), the connection indicators, add-form defaults and options are refreshed, the library and calendar reload, the Downloads interval, notifications, bell and poster style are switched live. - **Config view (F6):** one list with a field for every setting of the config file, one below the other under the headings Radarr, Sonarr, SABnzbd and Interface (a single scrolling form; ↑↓ passes over the headings and ↓ after the last field reaches the Save / Revert buttons, so no Tab is needed; Tab jumps between the fields and the buttons). The `Test` button is part of the list, right below the SABnzbd settings; `Save` and `Revert` are centered in a bar below the list. When the config file does not exist, it is created empty (`config.Create`: directory `0700`, file `0600`) and the program opens on this view. A service with neither address nor key is "not configured": allowed by validation (half-filled ones are not), its client answers every call with `ErrNotConfigured` without a request, its indicator stays grey (logged once as information, not as unreachable) and its lists say "not configured (Config view, F6)" instead of an error. The fields start from the settings in use; API keys are masked (a checkbox shows them). The default quality profile and root folder of Radarr and Sonarr are dropdowns filled from the server (`/qualityprofile`, `/rootfolder`) with the address and key currently in the fields: when the view opens, on Revert, and 700 ms after the address or key was last changed; answers for values that have changed since are dropped, a failure is reported once in the result box. "(none)" comes first; a configured value the server does not list stays as an option, marked "(not on the server)", so opening the view never changes a setting. `Test` builds temporary clients from the typed values and reports each service. `Save` validates like startup does (URLs, non-empty keys, refresh 1–3600 s), then writes the file from the file's own contents plus the edits (`config.LoadFile`), so values that only come from `ARR_TUI_*` environment variables are left as the file has them and are shown greyed out; the write is atomic (temp file + rename) and keeps the file's permissions (`0600` when new); defaults such as `covers: true` stay out of the file unless it already named them. Everything then applies without a restart: the Radarr/Sonarr/SABnzbd clients are re-pointed (`Reconfigure`, guarded by a mutex), the connection indicators, add-form defaults and options are refreshed, the library and calendar reload, the Downloads interval, notifications, bell and poster style are switched live.
- **Notifications and log (F7):** feedback about actions (added, deleted, grabbed, failures) appears as popups in the bottom right that fade away (errors stay longer). Everything is also kept in the Log view; only connection changes of the background polling are logged, not every failed poll. - **Notifications and log (F7):** feedback about actions (added, deleted, grabbed, failures) appears as popups in the bottom right that fade away (errors stay longer). Everything is also kept in the Log view; only connection changes of the background polling are logged, not every failed poll.
### 4.2 v0.2 (done, M8) ### 4.2 v0.2 (done, M8)
+9
View File
@@ -2,8 +2,10 @@
package main package main
import ( import (
"errors"
"flag" "flag"
"fmt" "fmt"
"io/fs"
"os" "os"
"git.stinnesbeck.com/nils/arr-tui/internal/config" "git.stinnesbeck.com/nils/arr-tui/internal/config"
@@ -38,6 +40,13 @@ func run() error {
*path = p *path = p
} }
// No config yet (first start): create an empty one, the Config view fills it in.
if _, err := os.Stat(*path); errors.Is(err, fs.ErrNotExist) {
if err := config.Create(*path); err != nil {
return err
}
}
cfg, warnings, err := config.Load(*path) cfg, warnings, err := config.Load(*path)
if err != nil { if err != nil {
return err return err
Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

+7
View File
@@ -48,6 +48,10 @@ func NewClient(baseURL, apiKey string) *Client {
} }
} }
// ErrNotConfigured is returned without a request while the client has no
// address: the service is not set up.
var ErrNotConfigured = errors.New("not configured: enter its address and API key in the Config view (F6)")
// APIError is returned for non-2xx responses. // APIError is returned for non-2xx responses.
type APIError struct { type APIError struct {
Status int Status int
@@ -65,6 +69,9 @@ func (e *APIError) Error() string {
// the response is decoded into out (if non-nil). // the response is decoded into out (if non-nil).
func (c *Client) Do(ctx context.Context, method, path string, query url.Values, body, out any) error { func (c *Client) Do(ctx context.Context, method, path string, query url.Values, body, out any) error {
base, apiKey := c.settings() base, apiKey := c.settings()
if base == "" {
return ErrNotConfigured
}
u := base + "/api/v3/" + strings.TrimLeft(path, "/") u := base + "/api/v3/" + strings.TrimLeft(path, "/")
if len(query) > 0 { if len(query) > 0 {
u += "?" + query.Encode() u += "?" + query.Encode()
+26 -15
View File
@@ -7,6 +7,7 @@ import (
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"strconv"
"strings" "strings"
"time" "time"
) )
@@ -17,10 +18,11 @@ const maxImageBytes = 8 << 20
// function that downloads it, or ok=false when there is none. // function that downloads it, or ok=false when there is none.
// //
// Library items have a copy on the Radarr/Sonarr server, which is fetched // Library items have a copy on the Radarr/Sonarr server, which is fetched
// with the API key (preferring the small -250 variant). Titles that are not // with the API key, preferring a scaled variant: -250 (250×375), or -500
// in the library yet only have the remote URL of the metadata provider; that // (500×750) when fetch is asked for a large poster. Titles that are not in
// is fetched without the API key. // the library yet only have the remote URL of the metadata provider; that is
func (c *Client) Poster(images []Image, inLibrary bool) (key string, fetch func(ctx context.Context) ([]byte, error), ok bool) { // fetched without the API key.
func (c *Client) Poster(images []Image, inLibrary bool) (key string, fetch func(ctx context.Context, large bool) ([]byte, error), ok bool) {
for _, img := range images { for _, img := range images {
if img.CoverType != "poster" { if img.CoverType != "poster" {
continue continue
@@ -28,8 +30,8 @@ func (c *Client) Poster(images []Image, inLibrary bool) (key string, fetch func(
if inLibrary && img.URL != "" { if inLibrary && img.URL != "" {
local, remote := img.URL, img.RemoteURL local, remote := img.URL, img.RemoteURL
base, _ := c.settings() base, _ := c.settings()
return base + "|" + local, func(ctx context.Context) ([]byte, error) { return base + "|" + local, func(ctx context.Context, large bool) ([]byte, error) {
data, err := c.localPoster(ctx, local) data, err := c.localPoster(ctx, local, large)
if err != nil && remote != "" { if err != nil && remote != "" {
// The instance has no usable copy (not cached, or behind a login): // The instance has no usable copy (not cached, or behind a login):
// use the metadata provider's, as for titles not in the library. // use the metadata provider's, as for titles not in the library.
@@ -42,17 +44,17 @@ func (c *Client) Poster(images []Image, inLibrary bool) (key string, fetch func(
} }
if img.RemoteURL != "" { if img.RemoteURL != "" {
remote := img.RemoteURL remote := img.RemoteURL
return remote, func(ctx context.Context) ([]byte, error) { return FetchURL(ctx, remote) }, true return remote, func(ctx context.Context, _ bool) ([]byte, error) { return FetchURL(ctx, remote) }, true
} }
} }
return "", nil, false return "", nil, false
} }
// localPoster fetches a poster from the instance: the small variant, then the // localPoster fetches a poster from the instance: the scaled variant (-500
// original. When the instance answers with a page instead of an image (it // when large, else -250), then the original. When the instance answers with a page instead of an image (it
// wants a login for /MediaCover) the API key is also tried as a query // wants a login for /MediaCover) the API key is also tried as a query
// parameter, which is the other way Radarr and Sonarr accept it. // parameter, which is the other way Radarr and Sonarr accept it.
func (c *Client) localPoster(ctx context.Context, local string) ([]byte, error) { func (c *Client) localPoster(ctx context.Context, local string, large bool) ([]byte, error) {
try := func(ref string) ([]byte, error) { try := func(ref string) ([]byte, error) {
data, err := c.GetBytes(ctx, ref) data, err := c.GetBytes(ctx, ref)
var page *notImageError var page *notImageError
@@ -63,8 +65,12 @@ func (c *Client) localPoster(ctx context.Context, local string) ([]byte, error)
} }
return data, err return data, err
} }
if small := smallVariant(local); small != local { width := 250
data, err := try(small) if large {
width = 500
}
if scaled := scaledVariant(local, width); scaled != local {
data, err := try(scaled)
if err == nil { if err == nil {
return data, nil return data, nil
} }
@@ -76,13 +82,15 @@ func (c *Client) localPoster(ctx context.Context, local string) ([]byte, error)
return try(local) return try(local)
} }
// smallVariant turns /MediaCover/1/poster.jpg?x into /MediaCover/1/poster-250.jpg?x. // scaledVariant turns /MediaCover/1/poster.jpg?x into
func smallVariant(p string) string { // /MediaCover/1/poster-250.jpg?x (for width 250; Radarr and Sonarr keep 250
// and 500).
func scaledVariant(p string, width int) string {
path, query, hasQuery := strings.Cut(p, "?") path, query, hasQuery := strings.Cut(p, "?")
if !strings.HasSuffix(path, "/poster.jpg") { if !strings.HasSuffix(path, "/poster.jpg") {
return p return p
} }
path = strings.TrimSuffix(path, ".jpg") + "-250.jpg" path = strings.TrimSuffix(path, ".jpg") + "-" + strconv.Itoa(width) + ".jpg"
if hasQuery { if hasQuery {
return path + "?" + query return path + "?" + query
} }
@@ -135,6 +143,9 @@ func (e *notImageError) Error() string {
// their URL base in image paths, so it must not be added twice. // their URL base in image paths, so it must not be added twice.
func (c *Client) resolve(ref string) (string, error) { func (c *Client) resolve(ref string) (string, error) {
baseURL, _ := c.settings() baseURL, _ := c.settings()
if baseURL == "" {
return "", ErrNotConfigured
}
base, err := url.Parse(baseURL) base, err := url.Parse(baseURL)
if err != nil { if err != nil {
return "", err return "", err
+38 -14
View File
@@ -8,18 +8,42 @@ import (
"testing" "testing"
) )
func TestSmallVariant(t *testing.T) { func TestScaledVariant(t *testing.T) {
for in, want := range map[string]string{ for _, tc := range []struct {
"/MediaCover/1/poster.jpg?lastWrite=5": "/MediaCover/1/poster-250.jpg?lastWrite=5", in string
"/MediaCover/1/poster.jpg": "/MediaCover/1/poster-250.jpg", width int
"/MediaCover/1/fanart.jpg": "/MediaCover/1/fanart.jpg", want string
}{
{"/MediaCover/1/poster.jpg?lastWrite=5", 250, "/MediaCover/1/poster-250.jpg?lastWrite=5"},
{"/MediaCover/1/poster.jpg", 500, "/MediaCover/1/poster-500.jpg"},
{"/MediaCover/1/fanart.jpg", 250, "/MediaCover/1/fanart.jpg"},
} { } {
if got := smallVariant(in); got != want { if got := scaledVariant(tc.in, tc.width); got != tc.want {
t.Errorf("smallVariant(%q) = %q, want %q", in, got, want) t.Errorf("scaledVariant(%q, %d) = %q, want %q", tc.in, tc.width, got, tc.want)
} }
} }
} }
func TestLargePosterUsesThe500Variant(t *testing.T) {
var paths []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paths = append(paths, r.URL.Path)
w.Write([]byte("IMG"))
}))
defer srv.Close()
c := NewClient(srv.URL, "secret")
_, fetch, _ := c.Poster([]Image{{CoverType: "poster", URL: "/MediaCover/1/poster.jpg"}}, true)
if _, err := fetch(context.Background(), true); err != nil {
t.Fatal(err)
}
if _, err := fetch(context.Background(), false); err != nil {
t.Fatal(err)
}
if strings.Join(paths, " ") != "/MediaCover/1/poster-500.jpg /MediaCover/1/poster-250.jpg" {
t.Errorf("requests = %v", paths)
}
}
func TestPosterLocalUsesAPIKey(t *testing.T) { func TestPosterLocalUsesAPIKey(t *testing.T) {
var paths []string var paths []string
var keys []string var keys []string
@@ -40,7 +64,7 @@ func TestPosterLocalUsesAPIKey(t *testing.T) {
if !ok || key == "" { if !ok || key == "" {
t.Fatal("no poster") t.Fatal("no poster")
} }
data, err := fetch(context.Background()) data, err := fetch(context.Background(), false)
if err != nil || string(data) != "IMG" { if err != nil || string(data) != "IMG" {
t.Fatalf("data=%q err=%v", data, err) t.Fatalf("data=%q err=%v", data, err)
} }
@@ -67,7 +91,7 @@ func TestPosterRemoteSendsNoAPIKey(t *testing.T) {
if !ok || key != srv.URL+"/p.jpg" { if !ok || key != srv.URL+"/p.jpg" {
t.Fatalf("key=%q ok=%v", key, ok) t.Fatalf("key=%q ok=%v", key, ok)
} }
if _, err := fetch(context.Background()); err != nil { if _, err := fetch(context.Background(), false); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if got != "" { if got != "" {
@@ -111,7 +135,7 @@ func TestPosterFallsBackToTheProviderWhenTheInstanceHasNoCopy(t *testing.T) {
if !ok { if !ok {
t.Fatal("no poster") t.Fatal("no poster")
} }
data, err := fetch(context.Background()) data, err := fetch(context.Background(), false)
if err != nil || string(data) != "REMOTE" { if err != nil || string(data) != "REMOTE" {
t.Fatalf("data=%q err=%v", data, err) t.Fatalf("data=%q err=%v", data, err)
} }
@@ -121,7 +145,7 @@ func TestPosterFallsBackToTheProviderWhenTheInstanceHasNoCopy(t *testing.T) {
// Without a remote address the local failure is reported. // Without a remote address the local failure is reported.
_, fetch, _ = c.Poster([]Image{{CoverType: "poster", URL: "/MediaCover/9/poster.jpg"}}, true) _, fetch, _ = c.Poster([]Image{{CoverType: "poster", URL: "/MediaCover/9/poster.jpg"}}, true)
if _, err := fetch(context.Background()); err == nil { if _, err := fetch(context.Background(), false); err == nil {
t.Error("expected the local error") t.Error("expected the local error")
} }
} }
@@ -148,7 +172,7 @@ func TestPosterTriesTheKeyInTheQueryWhenGivenALoginPage(t *testing.T) {
c := NewClient(srv.URL, "secret") c := NewClient(srv.URL, "secret")
_, fetch, _ := c.Poster([]Image{{CoverType: "poster", URL: "/MediaCover/89/poster.jpg"}}, true) _, fetch, _ := c.Poster([]Image{{CoverType: "poster", URL: "/MediaCover/89/poster.jpg"}}, true)
data, err := fetch(context.Background()) data, err := fetch(context.Background(), false)
if err != nil || string(data) != "IMAGE" { if err != nil || string(data) != "IMAGE" {
t.Fatalf("data=%q err=%v, hits=%v", data, err, hits) t.Fatalf("data=%q err=%v, hits=%v", data, err, hits)
} }
@@ -173,7 +197,7 @@ func TestPosterUsesTheProviderWhenTheInstanceOnlyShowsALogin(t *testing.T) {
c := NewClient(instance.URL, "secret") c := NewClient(instance.URL, "secret")
_, fetch, _ := c.Poster([]Image{{CoverType: "poster", URL: "/MediaCover/89/poster.jpg", RemoteURL: remote.URL + "/p.jpg"}}, true) _, fetch, _ := c.Poster([]Image{{CoverType: "poster", URL: "/MediaCover/89/poster.jpg", RemoteURL: remote.URL + "/p.jpg"}}, true)
data, err := fetch(context.Background()) data, err := fetch(context.Background(), false)
if err != nil || string(data) != "WEBP" { if err != nil || string(data) != "WEBP" {
t.Fatalf("data=%q err=%v", data, err) t.Fatalf("data=%q err=%v", data, err)
} }
@@ -186,7 +210,7 @@ func TestPosterUsesTheProviderWhenTheInstanceOnlyShowsALogin(t *testing.T) {
// Without a provider address the failure says what came back. // Without a provider address the failure says what came back.
_, fetch, _ = c.Poster([]Image{{CoverType: "poster", URL: "/MediaCover/89/poster.jpg"}}, true) _, fetch, _ = c.Poster([]Image{{CoverType: "poster", URL: "/MediaCover/89/poster.jpg"}}, true)
_, err = fetch(context.Background()) _, err = fetch(context.Background(), false)
if err == nil || !strings.Contains(err.Error(), "text/html") || !strings.Contains(err.Error(), "login") { if err == nil || !strings.Contains(err.Error(), "text/html") || !strings.Contains(err.Error(), "login") {
t.Errorf("error = %v", err) t.Errorf("error = %v", err)
} }
+24 -1
View File
@@ -18,6 +18,24 @@ type Service struct {
APIKey string `json:"apikey"` APIKey string `json:"apikey"`
} }
// Configured reports whether the service is set up at all (address or key
// given). Validate checks that a configured service has both.
func (s Service) Configured() bool { return s.URL != "" || s.APIKey != "" }
// AnyConfigured reports whether at least one service is set up.
func (c *Config) AnyConfigured() bool {
return c.Radarr.Configured() || c.Sonarr.Configured() || c.SABnzbd.Configured()
}
// Create writes an empty configuration to path, creating its directory
// (private, like the file). Every service is not set up yet.
func Create(path string) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return fmt.Errorf("creating config directory: %w", err)
}
return Save(path, &Config{})
}
// Arr is a Radarr or Sonarr instance, with optional defaults for the add form. // Arr is a Radarr or Sonarr instance, with optional defaults for the add form.
type Arr struct { type Arr struct {
Service Service
@@ -246,7 +264,9 @@ func (c *Config) applyDefaults() {
c.SABnzbd.URL = strings.TrimRight(c.SABnzbd.URL, "/") c.SABnzbd.URL = strings.TrimRight(c.SABnzbd.URL, "/")
} }
// Validate checks that every service has a usable URL and API key. // Validate checks that every service that is set up has a usable URL and API
// key. A service with neither is not set up, which is allowed: the program
// starts without it and says so, and the Config view can fill it in.
func (c *Config) Validate() error { func (c *Config) Validate() error {
var errs []error var errs []error
for _, s := range []struct { for _, s := range []struct {
@@ -257,6 +277,9 @@ func (c *Config) Validate() error {
{"sonarr", c.Sonarr.Service}, {"sonarr", c.Sonarr.Service},
{"sabnzbd", c.SABnzbd}, {"sabnzbd", c.SABnzbd},
} { } {
if !s.svc.Configured() {
continue // not set up (yet); the program says so where it is needed
}
if s.svc.APIKey == "" { if s.svc.APIKey == "" {
errs = append(errs, fmt.Errorf("%s: apikey is required", s.name)) errs = append(errs, fmt.Errorf("%s: apikey is required", s.name))
} }
+33
View File
@@ -35,6 +35,7 @@ func TestParseErrors(t *testing.T) {
"missing key": {`{"radarr":{"url":"http://a"},"sonarr":{"url":"http://b","apikey":"x"},"sabnzbd":{"url":"http://c","apikey":"x"}}`, "radarr: apikey is required"}, "missing key": {`{"radarr":{"url":"http://a"},"sonarr":{"url":"http://b","apikey":"x"},"sabnzbd":{"url":"http://c","apikey":"x"}}`, "radarr: apikey is required"},
"bad url": {`{"radarr":{"url":"localhost","apikey":"x"},"sonarr":{"url":"http://b","apikey":"x"},"sabnzbd":{"url":"http://c","apikey":"x"}}`, "must be an http(s) URL"}, "bad url": {`{"radarr":{"url":"localhost","apikey":"x"},"sonarr":{"url":"http://b","apikey":"x"},"sabnzbd":{"url":"http://c","apikey":"x"}}`, "must be an http(s) URL"},
"invalid json": {`{`, "parsing config"}, "invalid json": {`{`, "parsing config"},
"key only": {`{"radarr":{"apikey":"x"}}`, "radarr: url is required"},
} }
for name, tc := range tests { for name, tc := range tests {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
@@ -200,3 +201,35 @@ func TestEffectiveValidates(t *testing.T) {
t.Error("an invalid config must not become effective") t.Error("an invalid config must not become effective")
} }
} }
func TestServicesMayBeLeftOut(t *testing.T) {
cfg, err := Parse([]byte(`{"radarr":{"url":"http://r","apikey":"k"}}`))
if err != nil {
t.Fatalf("a config with only Radarr must load: %v", err)
}
if !cfg.Radarr.Configured() || cfg.Sonarr.Configured() || cfg.SABnzbd.Configured() || !cfg.AnyConfigured() {
t.Errorf("configured: radarr %v sonarr %v sab %v", cfg.Radarr.Configured(), cfg.Sonarr.Configured(), cfg.SABnzbd.Configured())
}
empty, err := Parse([]byte(`{}`))
if err != nil || empty.AnyConfigured() {
t.Errorf("an empty config must load with nothing set up: %v", err)
}
}
func TestCreate(t *testing.T) {
path := filepath.Join(t.TempDir(), "new", "dir", "config.json")
if err := Create(path); err != nil {
t.Fatal(err)
}
info, err := os.Stat(path)
if err != nil || info.Mode().Perm() != 0o600 {
t.Fatalf("file: %v %v", info, err)
}
if dir, _ := os.Stat(filepath.Dir(path)); dir.Mode().Perm() != 0o700 {
t.Errorf("directory mode %v", dir.Mode().Perm())
}
cfg, warnings, err := Load(path)
if err != nil || len(warnings) > 0 || cfg.AnyConfigured() {
t.Errorf("the new file must load cleanly: %v %v", warnings, err)
}
}
+7
View File
@@ -40,6 +40,10 @@ func NewClient(baseURL, apiKey string) *Client {
} }
} }
// ErrNotConfigured is returned without a request while the client has no
// address: the service is not set up.
var ErrNotConfigured = errors.New("not configured: enter its address and API key in the Config view (F6)")
// Number is a float that SABnzbd sends either as a JSON number or as a string ("0.48"). // Number is a float that SABnzbd sends either as a JSON number or as a string ("0.48").
type Number float64 type Number float64
@@ -172,6 +176,9 @@ func (c *Client) call(ctx context.Context, params url.Values, out any) error {
c.mu.RLock() c.mu.RLock()
baseURL, apiKey := c.baseURL, c.apiKey baseURL, apiKey := c.baseURL, c.apiKey
c.mu.RUnlock() c.mu.RUnlock()
if baseURL == "" {
return ErrNotConfigured
}
params.Set("apikey", apiKey) params.Set("apikey", apiKey)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/api?"+params.Encode(), nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/api?"+params.Encode(), nil)
+30 -2
View File
@@ -3,6 +3,7 @@ package ui
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"os" "os"
"strings" "strings"
@@ -11,6 +12,7 @@ import (
"github.com/gdamore/tcell/v2" "github.com/gdamore/tcell/v2"
"github.com/rivo/tview" "github.com/rivo/tview"
"git.stinnesbeck.com/nils/arr-tui/internal/arr"
"git.stinnesbeck.com/nils/arr-tui/internal/config" "git.stinnesbeck.com/nils/arr-tui/internal/config"
"git.stinnesbeck.com/nils/arr-tui/internal/radarr" "git.stinnesbeck.com/nils/arr-tui/internal/radarr"
"git.stinnesbeck.com/nils/arr-tui/internal/sabnzbd" "git.stinnesbeck.com/nils/arr-tui/internal/sabnzbd"
@@ -203,6 +205,11 @@ func New(cfg *config.Config) *App {
syncFocus = func(p tview.Primitive) { a.app.SetFocus(p) } syncFocus = func(p tview.Primitive) { a.app.SetFocus(p) }
a.app.SetInputCapture(a.handleKey) a.app.SetInputCapture(a.handleKey)
a.switchTo(0) a.switchTo(0)
if !cfg.AnyConfigured() {
// First start (or nothing set up): go where that is done.
a.switchTo(a.viewIndex("Config"))
a.Notify(levelInfo, "Welcome! Enter the addresses and API keys of your services, then Save")
}
a.renderServices() a.renderServices()
return a return a
} }
@@ -314,7 +321,11 @@ func (a *App) SetService(name, version string, err error) {
a.state[name] = serviceState{known: true, version: version, err: err} a.state[name] = serviceState{known: true, version: version, err: err}
// Log connection changes only, so background polling does not flood the log. // Log connection changes only, so background polling does not flood the log.
switch { switch {
case err != nil && (!prev.known || prev.err == nil): case notConfigured(err):
if !prev.known || !notConfigured(prev.err) {
a.logs.add(levelInfo, name+" is not configured; set it up in the Config view (F6)")
}
case err != nil && (!prev.known || prev.err == nil || notConfigured(prev.err)):
a.logs.add(levelError, name+" unreachable: "+err.Error()) a.logs.add(levelError, name+" unreachable: "+err.Error())
case err == nil && (!prev.known || prev.err != nil): case err == nil && (!prev.known || prev.err != nil):
a.logs.add(levelSuccess, strings.TrimSpace(name+" "+version)+" connected") a.logs.add(levelSuccess, strings.TrimSpace(name+" "+version)+" connected")
@@ -354,7 +365,7 @@ func (a *App) renderServices() {
} }
st := a.state[n] st := a.state[n]
switch { switch {
case !st.known: case !st.known, notConfigured(st.err):
s += "[gray]○ " + short + "[-] " s += "[gray]○ " + short + "[-] "
case st.err != nil: case st.err != nil:
s += "[red]● " + short + "[-] " s += "[red]● " + short + "[-] "
@@ -373,6 +384,8 @@ func (a *App) serviceSummary() string {
switch { switch {
case !st.known: case !st.known:
fmt.Fprintf(&b, "[gray]○ %s: not contacted yet[-]\n", n) fmt.Fprintf(&b, "[gray]○ %s: not contacted yet[-]\n", n)
case notConfigured(st.err):
fmt.Fprintf(&b, "[gray]○ %s: not configured (Config view, F6)[-]\n", n)
case st.err != nil: case st.err != nil:
fmt.Fprintf(&b, "[red]● %s: %s[-]\n", n, tview.Escape(st.err.Error())) fmt.Fprintf(&b, "[red]● %s: %s[-]\n", n, tview.Escape(st.err.Error()))
case st.version != "": case st.version != "":
@@ -384,6 +397,21 @@ func (a *App) serviceSummary() string {
return b.String() return b.String()
} }
// viewIndex returns the position of the view with the given name.
func (a *App) viewIndex(name string) int {
for i, v := range a.views {
if v.name == name {
return i
}
}
return 0
}
// notConfigured reports whether err says a service is not set up.
func notConfigured(err error) bool {
return errors.Is(err, arr.ErrNotConfigured) || errors.Is(err, sabnzbd.ErrNotConfigured)
}
// post runs f on the UI goroutine and redraws. Safe to call from any goroutine. // post runs f on the UI goroutine and redraws. Safe to call from any goroutine.
func (a *App) post(f func()) { func (a *App) post(f func()) {
a.app.QueueUpdateDraw(f) a.app.QueueUpdateDraw(f)
+35
View File
@@ -1,11 +1,15 @@
package ui package ui
import ( import (
"errors"
"strings"
"testing" "testing"
"github.com/gdamore/tcell/v2" "github.com/gdamore/tcell/v2"
"git.stinnesbeck.com/nils/arr-tui/internal/arr"
"git.stinnesbeck.com/nils/arr-tui/internal/config" "git.stinnesbeck.com/nils/arr-tui/internal/config"
"git.stinnesbeck.com/nils/arr-tui/internal/sabnzbd"
) )
func newTestApp(t *testing.T) *App { func newTestApp(t *testing.T) *App {
@@ -46,3 +50,34 @@ func TestQDoesNotQuit(t *testing.T) {
t.Error("q must be passed on as an ordinary key, not taken as quit") t.Error("q must be passed on as an ordinary key, not taken as quit")
} }
} }
func TestStartsWithoutServices(t *testing.T) {
// The config a first start creates: nothing set up.
a := New(&config.Config{UI: config.UI{RefreshSeconds: 3}})
if a.views[a.active].name != "Config" {
t.Errorf("first start opens %q, want the Config view", a.views[a.active].name)
}
// The clients do not try to connect without an address.
_, err := a.radarr.SystemStatus(t.Context())
if !errors.Is(err, arr.ErrNotConfigured) {
t.Fatalf("radarr without address: %v", err)
}
if _, err := a.sab.Version(t.Context()); !errors.Is(err, sabnzbd.ErrNotConfigured) {
t.Fatalf("sabnzbd without address: %v", err)
}
// Not configured is grey, not red, and logged once as information.
a.SetService("Radarr", "", err)
a.SetService("Radarr", "", err)
if txt := a.services.GetText(false); !strings.Contains(txt, "○ Radarr") {
t.Errorf("indicator: %q", txt)
}
log := a.logs.root.GetText(true)
if strings.Count(log, "Radarr is not configured") != 1 || strings.Contains(log, "unreachable") {
t.Errorf("log: %q", log)
}
if !strings.Contains(a.serviceSummary(), "Radarr: not configured") {
t.Errorf("help summary: %q", a.serviceSummary())
}
}
+4 -2
View File
@@ -294,12 +294,14 @@ func (v *calendarView) reload() {
if gen != v.gen { if gen != v.gen {
return return
} }
// A service that is not set up just contributes nothing.
usable := func(err error) bool { return err == nil || notConfigured(err) }
for _, err := range []error{movieErr, tvErr} { for _, err := range []error{movieErr, tvErr} {
if err != nil { if !usable(err) {
v.app.SetMessage("[red]Calendar: " + tview.Escape(err.Error())) v.app.SetMessage("[red]Calendar: " + tview.Escape(err.Error()))
} }
} }
if movieErr == nil || tvErr == nil { // show what we got if usable(movieErr) || usable(tvErr) { // show what we got
v.entries, v.loaded = entries, true v.entries, v.loaded = entries, true
} }
v.render() v.render()
+3 -2
View File
@@ -468,7 +468,7 @@ func (c *coverView) build(cols, rows int) []styledCell {
// coverRef says where a poster comes from. The zero value means "no poster". // coverRef says where a poster comes from. The zero value means "no poster".
type coverRef struct { type coverRef struct {
key string // identifies the poster in the cache key string // identifies the poster in the cache
fetch func(ctx context.Context) ([]byte, error) fetch func(ctx context.Context, large bool) ([]byte, error) // large: for real images
} }
// coverFor builds the poster reference of a title from its image list. // coverFor builds the poster reference of a title from its image list.
@@ -516,6 +516,7 @@ func (a *App) loadCover(ref coverRef, done func(*image.RGBA, error)) {
} }
c.waiting[ref.key] = []func(*image.RGBA, error){done} c.waiting[ref.key] = []func(*image.RGBA, error){done}
maxHeight := a.coverMaxHeight() maxHeight := a.coverMaxHeight()
large := a.gfx != nil // real images show the poster at full resolution
go func() { go func() {
c.slots <- struct{}{} c.slots <- struct{}{}
@@ -523,7 +524,7 @@ func (a *App) loadCover(ref coverRef, done func(*image.RGBA, error)) {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel() defer cancel()
var img *image.RGBA var img *image.RGBA
data, err := ref.fetch(ctx) data, err := ref.fetch(ctx, large)
if err == nil { if err == nil {
img, err = decodeCover(data, maxHeight) img, err = decodeCover(data, maxHeight)
} }
+2 -2
View File
@@ -165,7 +165,7 @@ func TestLoadCoverCachesAndDedupes(t *testing.T) {
var fetches atomic.Int32 var fetches atomic.Int32
var buf bytes.Buffer var buf bytes.Buffer
png.Encode(&buf, stripes(10, 20)) png.Encode(&buf, stripes(10, 20))
ref := coverRef{key: "k", fetch: func(context.Context) ([]byte, error) { ref := coverRef{key: "k", fetch: func(context.Context, bool) ([]byte, error) {
fetches.Add(1) fetches.Add(1)
return buf.Bytes(), nil return buf.Bytes(), nil
}} }}
@@ -186,7 +186,7 @@ func TestLoadCoverRemembersFailures(t *testing.T) {
a := newTestApp(t) a := newTestApp(t)
a.coverCache.failed["bad"] = time.Now() a.coverCache.failed["bad"] = time.Now()
var gotErr error var gotErr error
a.loadCover(coverRef{key: "bad", fetch: func(context.Context) ([]byte, error) { a.loadCover(coverRef{key: "bad", fetch: func(context.Context, bool) ([]byte, error) {
t.Error("a recent failure must not be retried") t.Error("a recent failure must not be retried")
return nil, nil return nil, nil
}}, func(_ *image.RGBA, err error) { gotErr = err }) }}, func(_ *image.RGBA, err error) { gotErr = err })
+1 -1
View File
@@ -116,7 +116,7 @@ func TestPosterWaitsWhileTheSelectionMoves(t *testing.T) {
img := image.NewRGBA(image.Rect(0, 0, 20, 30)) img := image.NewRGBA(image.Rect(0, 0, 20, 30))
a.coverCache.imgs["one"], a.coverCache.imgs["two"] = img, img a.coverCache.imgs["one"], a.coverCache.imgs["two"] = img, img
ref := func(key string) coverRef { ref := func(key string) coverRef {
return coverRef{key: key, fetch: func(context.Context) ([]byte, error) { return nil, nil }} return coverRef{key: key, fetch: func(context.Context, bool) ([]byte, error) { return nil, nil }}
} }
d := newDetailPane(a) d := newDetailPane(a)
+17 -2
View File
@@ -35,6 +35,7 @@ type downloadsView struct {
sab *sabnzbd.Client sab *sabnzbd.Client
sources []arrSource sources []arrSource
interval time.Duration interval time.Duration
sabUnset bool // SABnzbd is not set up: its lists say so instead of "empty"
root *tview.Flex root *tview.Flex
summary *tview.TextView summary *tview.TextView
@@ -210,6 +211,12 @@ func (v *downloadsView) refresh(ctx context.Context) {
v.app.post(func() { v.app.post(func() {
v.app.SetService("SABnzbd", "", qerr) v.app.SetService("SABnzbd", "", qerr)
if unset := notConfigured(qerr); unset != v.sabUnset {
v.sabUnset = unset
v.sabQueue, v.slots, v.done = sabnzbd.Queue{}, nil, nil
v.renderQueue()
v.renderHistory()
}
if qerr == nil { if qerr == nil {
v.sabQueue, v.slots, v.paused = queue, queue.Slots, queue.Paused v.sabQueue, v.slots, v.paused = queue, queue.Slots, queue.Paused
v.renderQueue() v.renderQueue()
@@ -230,6 +237,14 @@ func (v *downloadsView) refresh(ctx context.Context) {
}) })
} }
// sabPlaceholder is what an empty SABnzbd list says.
func (v *downloadsView) sabPlaceholder(empty string) string {
if v.sabUnset {
return "SABnzbd is not configured (Config view, F6)"
}
return empty
}
func (v *downloadsView) rebuildArrRows() { func (v *downloadsView) rebuildArrRows() {
v.arrRows = v.arrRows[:0] v.arrRows = v.arrRows[:0]
for _, s := range v.sources { for _, s := range v.sources {
@@ -331,7 +346,7 @@ func (v *downloadsView) renderQueue() {
} }
} }
fill(v.queue, 0, rows) fill(v.queue, 0, rows)
restoreSelection(v.queue, len(rows), selRow, "Queue is empty") restoreSelection(v.queue, len(rows), selRow, v.sabPlaceholder("Queue is empty"))
} }
func (v *downloadsView) renderArr() { func (v *downloadsView) renderArr() {
@@ -414,7 +429,7 @@ func (v *downloadsView) renderHistory() {
} }
} }
fill(v.history, 0, rows) fill(v.history, 0, rows)
restoreSelection(v.history, len(rows), selRow, "No history") restoreSelection(v.history, len(rows), selRow, v.sabPlaceholder("No history"))
} }
// act runs an action off the UI goroutine, reports the outcome and refreshes. // act runs an action off the UI goroutine, reports the outcome and refreshes.
+7 -2
View File
@@ -363,8 +363,11 @@ func (v *libraryView) reloadPane(p *libPane) {
defer v.loadSeriesFiles(false) defer v.loadSeriesFiles(false)
} }
if err != nil { if err != nil {
// Keep showing the last good list; say why it is stale. // Keep showing the last good list; say why it is stale. A service
v.app.SetMessage("[red]" + kind.service() + ": " + tview.Escape(err.Error())) // that is not set up says so in its list instead.
if !notConfigured(err) {
v.app.SetMessage("[red]" + kind.service() + ": " + tview.Escape(err.Error()))
}
} else { } else {
p.all, p.loaded = items, true p.all, p.loaded = items, true
} }
@@ -418,6 +421,8 @@ func (v *libraryView) renderPane(p *libPane) {
} }
placeholder := "Nothing matches the filter" placeholder := "Nothing matches the filter"
switch { switch {
case notConfigured(p.err):
placeholder = p.kind.service() + " is not configured (Config view, F6)"
case p.err != nil && !p.loaded: case p.err != nil && !p.loaded:
placeholder = "Could not load, press r to retry" placeholder = "Could not load, press r to retry"
case !p.loaded: case !p.loaded:
+4
View File
@@ -382,6 +382,9 @@ func (v *settingsView) describe() {
b.WriteString("Config file: " + tview.Escape(v.app.cfgPath) + "\n") b.WriteString("Config file: " + tview.Escape(v.app.cfgPath) + "\n")
} }
b.WriteString("Changes take effect when you save; nothing needs a restart.\n") b.WriteString("Changes take effect when you save; nothing needs a restart.\n")
if !v.app.cfg.AnyConfigured() {
b.WriteString("[yellow]No service is set up yet.[-] Enter the address and API key of Radarr, Sonarr and/or SABnzbd (Settings → General in each app), then Save. A service left empty is simply not used.\n")
}
if len(v.overridden) > 0 { if len(v.overridden) > 0 {
var names []string var names []string
for _, env := range v.overridden { for _, env := range v.overridden {
@@ -478,6 +481,7 @@ func (v *settingsView) save() {
v.app.cfgFile = &raw v.app.cfgFile = &raw
v.app.applyConfig(effective) v.app.applyConfig(effective)
v.dirty = false v.dirty = false
v.describe() // what it says may depend on the settings (e.g. nothing set up yet)
v.report("[green]Saved to " + tview.Escape(v.app.cfgPath) + " and applied.[-]") v.report("[green]Saved to " + tview.Escape(v.app.cfgPath) + " and applied.[-]")
v.app.Notify(levelSuccess, "Settings saved") v.app.Notify(levelSuccess, "Settings saved")
} }