Compare commits

..

50 Commits

Author SHA1 Message Date
Dark-Alex-17 6df68b8a66 tests: Addressed additional CR comments and added tests for tail-logs 2026-06-25 14:21:57 -06:00
Dark-Alex-17 cbca6bd916 fix: addressed code review comments 2026-06-25 14:11:18 -06:00
Dark-Alex-17 92187c5f16 fix: tail-logs subcommand follows log rollovers and sleeps to minimize idle CPU loops 2026-06-25 13:51:32 -06:00
Dark-Alex-17 366809d8c6 fmt: applied formatting 2026-06-25 13:32:31 -06:00
Dark-Alex-17 dd93fe117d feat: Implemented log rolling so the log file doesn't just grow exponentially [#60] 2026-06-25 13:29:56 -06:00
Dark-Alex-17 10e18af1bf build: upgraded to openssl 0.10.79 to fix security vulnerabilities 2026-06-25 13:20:14 -06:00
Dark-Alex-17 a4d93692a9 build: Upgraded to Rust v1.95.0 2026-06-25 13:19:27 -06:00
Dark-Alex-17 03d134bec9 refactor: Refactored several usages of sort_by_key and match guards to utilize newer Rust version APIs 2026-06-25 13:18:43 -06:00
Dark-Alex-17 4cad9e1755 docs: Improved the README to demonstrate what a truly minimal configuration looks like for each service and explain the "reasonable defaults" [#61] 2026-06-25 12:35:51 -06:00
github-actions[bot] adb76bb603 bump: version 0.7.1 → 0.7.2 [skip ci] 2026-04-20 22:37:15 +00:00
Alex Clarke d9a2b1c6c4 Merge pull request #59 from Dark-Alex-17/develop
Check / stable / fmt (push) Failing after 25s
Check / beta / clippy (push) Failing after 1m12s
Check / stable / clippy (push) Failing after 1m11s
Check / nightly / doc (push) Successful in 1m3s
Check / 1.89.0 / check (push) Successful in 1m6s
Test Suite / ubuntu / beta (push) Successful in 1m46s
Test Suite / ubuntu / stable (push) Successful in 1m47s
Test Suite / ubuntu / stable / coverage (push) Failing after 2m19s
Test Suite / macos-latest / stable (push) Has been cancelled
Test Suite / windows-latest / stable (push) Has been cancelled
merge develop into main for release
2026-04-20 16:18:55 -06:00
Dark-Alex-17 47a2fbf0cc docs: removed the lines-of-code counter from the README since the link is dead 2026-04-20 16:02:18 -06:00
Dark-Alex-17 7067902752 build: updated reqwest and build dependencies 2026-04-20 15:53:42 -06:00
Dark-Alex-17 ba1cf0182b build: Updated the docker image so that it ships with trusted CA root certs from trusted providers like LetsEncrypt, DigiCert, etc. for docker SSL users 2026-04-02 09:58:30 -06:00
Dark-Alex-17 5cccec88c9 docs: Updated the README to have a more detailed section on how to acquire SSL certificate information 2026-03-30 10:13:51 -06:00
Dark-Alex-17 bbcd3f00a9 feat: Created a separate 'ssl' property for the config so users don't have to specify an ssl_cert_path to use SSL or use the uri workaround for HTTPS API access 2026-03-29 12:39:26 -06:00
Dark-Alex-17 2e339dd73b docs: Created an authorship policy and PR template that requires explicit acknowledgement of AI assistance 2026-02-24 17:41:34 -07:00
Dark-Alex-17 f988cf0f26 docs: Fixed some typos found in the README
Check / stable / fmt (push) Successful in 9m57s
Check / beta / clippy (push) Successful in 11m0s
Check / stable / clippy (push) Successful in 10m59s
Check / nightly / doc (push) Successful in 1m2s
Check / 1.89.0 / check (push) Successful in 1m9s
Test Suite / ubuntu / beta (push) Successful in 1m47s
Test Suite / ubuntu / stable (push) Successful in 1m43s
Test Suite / ubuntu / stable / coverage (push) Successful in 12m52s
Test Suite / macos-latest / stable (push) Has been cancelled
Test Suite / windows-latest / stable (push) Has been cancelled
2026-02-05 18:50:42 -07:00
Dark-Alex-17 ff82dc2012 style: Upgraded rustfmt edition to 2024
Check / stable / fmt (push) Successful in 9m57s
Check / beta / clippy (push) Successful in 11m0s
Check / stable / clippy (push) Successful in 10m59s
Check / nightly / doc (push) Successful in 57s
Check / 1.89.0 / check (push) Successful in 1m1s
Test Suite / ubuntu / beta (push) Successful in 1m43s
Test Suite / ubuntu / stable (push) Successful in 1m42s
Test Suite / ubuntu / stable / coverage (push) Successful in 12m52s
Test Suite / macos-latest / stable (push) Has been cancelled
Test Suite / windows-latest / stable (push) Has been cancelled
2026-02-05 10:47:35 -07:00
github-actions[bot] 89a692ad90 chore: bump Cargo.toml to 0.7.1
Check / stable / fmt (push) Successful in 9m55s
Check / beta / clippy (push) Successful in 10m59s
Check / stable / clippy (push) Successful in 10m59s
Check / nightly / doc (push) Successful in 59s
Check / 1.89.0 / check (push) Successful in 1m2s
Test Suite / ubuntu / beta (push) Successful in 1m42s
Test Suite / ubuntu / stable (push) Successful in 1m42s
Test Suite / ubuntu / stable / coverage (push) Successful in 12m51s
Test Suite / macos-latest / stable (push) Has been cancelled
Test Suite / windows-latest / stable (push) Has been cancelled
2026-02-04 18:01:02 +00:00
github-actions[bot] d77ec5fb34 bump: version 0.7.0 → 0.7.1 [skip ci] 2026-02-04 18:01:00 +00:00
Alex Clarke ec90e2dca7 Merge pull request #56 from Dark-Alex-17/develop
Check / stable / fmt (push) Successful in 9m53s
Check / beta / clippy (push) Has been cancelled
Check / stable / clippy (push) Has been cancelled
Check / nightly / doc (push) Has been cancelled
Check / 1.89.0 / check (push) Has been cancelled
Test Suite / ubuntu / beta (push) Has been cancelled
Test Suite / ubuntu / stable (push) Has been cancelled
Test Suite / macos-latest / stable (push) Has been cancelled
Test Suite / windows-latest / stable (push) Has been cancelled
Test Suite / ubuntu / stable / coverage (push) Has been cancelled
Hotfix and feature adds for some new issues
2026-02-04 10:38:58 -07:00
Dark-Alex-17 5a4e6c9623 style: Addressed CR comments about adding an explicit Command::ConfigPath to the main command match statement 2026-02-04 10:24:59 -07:00
Dark-Alex-17 9a6a06ee20 build: Updated all dependencies to resolve dependabot security issues 2026-02-04 09:51:57 -07:00
Dark-Alex-17 5556e48fc0 fix: Improved the system notification feature so it can persist between modals 2026-02-04 08:18:04 -07:00
Dark-Alex-17 af573cac2a feat: Added support for a system-wide notification popup mechanism that works across Servarrs 2026-02-03 17:03:12 -07:00
Dark-Alex-17 447cf6a2b4 style: Applied formatting to the artist_details_ui 2026-02-03 08:10:02 -07:00
Dark-Alex-17 203bf9cb66 fix: Sonarr API updated to somtimes allow either seeders or leechers to be null 2026-02-03 08:00:31 -07:00
Dark-Alex-17 4f9bc34d23 docs: Updated the README so that the example configuration only includes references to Servarrs that are actually supported [#55] 2026-01-30 15:45:22 -07:00
Dark-Alex-17 a2aa9507a9 fix: Improved the first-time run behavior so that it outputs the default configuration file it tries to load to help users locate the file on first-runs 2026-01-30 15:36:26 -07:00
Dark-Alex-17 c791b985f0 docs: Updated README to tell users to use 'managarr config-path' as the default method to discover the location of the default configuration file 2026-01-29 12:56:59 -07:00
Dark-Alex-17 5c517a748c fix: 'managarr config-path' should work without a pre-existing config already in place [#54] 2026-01-29 12:54:45 -07:00
Dark-Alex-17 892c687077 docs: Updated README with config-path as another way to find the default config file for a given system 2026-01-29 10:26:12 -07:00
Dark-Alex-17 c6d5b98e86 feat: Implemented a 'config-path' command to print out the default Managarr configuration file path to help address #54 2026-01-29 10:23:05 -07:00
Dark-Alex-17 67e5114ec2 build: Removed #[allow(dead_code)] from the LIDARR_LOGO since it is now being utilized 2026-01-26 11:56:05 -07:00
Dark-Alex-17 fdc331865e feat: Full support for filtering disks and aggregating root folders in the UI's 'Stats' block 2026-01-26 11:10:59 -07:00
Dark-Alex-17 f388dccc08 feat: proper collapsing of root folder paths in the stats layer of the UI 2026-01-22 14:44:48 -07:00
Dark-Alex-17 64fad3b9bc refactor: Removed the filtering of monitored_storage_paths from the networking module and migrated all of it to the UI 2026-01-22 13:12:51 -07:00
Dark-Alex-17 3be7b09da8 feat: Added config option to filter for specific disk space paths to display in the UI (CLI is unaffected) 2026-01-22 10:49:30 -07:00
Dark-Alex-17 5f3123cd79 test: Updated snapshot tests to assert the paths are updated in the UI
Check / stable / fmt (push) Successful in 9m57s
Check / beta / clippy (push) Successful in 10m59s
Check / stable / clippy (push) Successful in 10m59s
Check / nightly / doc (push) Successful in 59s
Check / 1.89.0 / check (push) Successful in 1m7s
Test Suite / ubuntu / beta (push) Successful in 1m48s
Test Suite / ubuntu / stable (push) Successful in 1m43s
Test Suite / ubuntu / stable / coverage (push) Successful in 12m55s
Test Suite / macos-latest / stable (push) Has been cancelled
Test Suite / windows-latest / stable (push) Has been cancelled
2026-01-22 09:39:44 -07:00
Dark-Alex-17 d8f7febfe1 feat: Improved disk-space UI and CLI that shows the actual path being monitored instead of just a disk number
Check / stable / fmt (push) Has been cancelled
Check / beta / clippy (push) Has been cancelled
Check / stable / clippy (push) Has been cancelled
Check / nightly / doc (push) Has been cancelled
Check / 1.89.0 / check (push) Has been cancelled
Test Suite / ubuntu / beta (push) Has been cancelled
Test Suite / ubuntu / stable (push) Has been cancelled
Test Suite / macos-latest / stable (push) Has been cancelled
Test Suite / windows-latest / stable (push) Has been cancelled
Test Suite / ubuntu / stable / coverage (push) Has been cancelled
2026-01-22 09:36:58 -07:00
Dark-Alex-17 0bfbb44e3e feat: Implemented the forgotten lidarr list disk-space command
Check / stable / fmt (push) Successful in 9m59s
Check / beta / clippy (push) Successful in 10m58s
Check / stable / clippy (push) Has been cancelled
Check / nightly / doc (push) Has been cancelled
Check / 1.89.0 / check (push) Has been cancelled
Test Suite / ubuntu / beta (push) Has been cancelled
Test Suite / ubuntu / stable (push) Has been cancelled
Test Suite / macos-latest / stable (push) Has been cancelled
Test Suite / windows-latest / stable (push) Has been cancelled
Test Suite / ubuntu / stable / coverage (push) Has been cancelled
2026-01-22 09:06:38 -07:00
github-actions[bot] c5161f828d chore: bump Cargo.toml to 0.7.0
Check / stable / fmt (push) Successful in 9m57s
Check / beta / clippy (push) Successful in 11m0s
Check / stable / clippy (push) Successful in 10m59s
Check / nightly / doc (push) Successful in 57s
Check / 1.89.0 / check (push) Successful in 1m0s
Test Suite / ubuntu / beta (push) Successful in 1m42s
Test Suite / ubuntu / stable (push) Successful in 1m42s
Test Suite / ubuntu / stable / coverage (push) Successful in 12m38s
Test Suite / macos-latest / stable (push) Has been cancelled
Test Suite / windows-latest / stable (push) Has been cancelled
2026-01-21 19:22:11 +00:00
github-actions[bot] 71c64167f0 bump: version 0.6.3 → 0.7.0 [skip ci] 2026-01-21 19:22:03 +00:00
Alex Clarke 4d3e00fd94 Merge pull request #52 from Dark-Alex-17/lidarr
Lidarr Support
2026-01-21 11:57:50 -07:00
Dark-Alex-17 9e96e74c87 ci: Fixed the docker-build Justfile recipe
Check / stable / fmt (pull_request) Successful in 10m40s
Check / beta / clippy (pull_request) Successful in 10m59s
Check / stable / clippy (pull_request) Successful in 10m59s
Check / nightly / doc (pull_request) Successful in 58s
Check / 1.89.0 / check (pull_request) Successful in 1m2s
Test Suite / ubuntu / beta (pull_request) Successful in 1m43s
Test Suite / ubuntu / stable (pull_request) Successful in 1m41s
Test Suite / ubuntu / stable / coverage (pull_request) Successful in 13m1s
Test Suite / macos-latest / stable (pull_request) Has been cancelled
Test Suite / windows-latest / stable (pull_request) Has been cancelled
2026-01-21 10:39:51 -07:00
Dark-Alex-17 ddb869c341 docs: Reword some Sonarr manual search CLI docs to be more explicit about how the results are filtered 2026-01-20 14:37:42 -07:00
Dark-Alex-17 f17f542e8e refactor: Refactored the SonarrEvent enum to not unnecessarily wrap dual series_id and season_number values in a tuple when both values can be passed directly 2026-01-19 16:44:10 -07:00
Dark-Alex-17 a2e6400a38 docs: Updated README with information about Lidarr support 2026-01-19 16:29:02 -07:00
Dark-Alex-17 89f5ff6bc7 feat: Blocklist support in Lidarr in both the CLI and TUI 2026-01-19 16:13:11 -07:00
167 changed files with 5410 additions and 1364 deletions
@@ -0,0 +1,11 @@
### AI assistance (if any):
- List tools here and files touched by them
### Authorship & Understanding
- [ ] I wrote or heavily modified this code myself
- [ ] I understand how it works end-to-end
- [ ] I can maintain this code in the future
- [ ] No undisclosed AI-generated code was used
- [ ] If AI assistance was used, it is documented below
+4 -4
View File
@@ -76,15 +76,15 @@ jobs:
RUSTDOCFLAGS: --cfg docsrs
msrv:
# check that we can build using the minimal rust version that is specified by this crate
name: 1.89.0 / check
name: 1.95.0 / check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install 1.89.0
- name: Install 1.95.0
uses: dtolnay/rust-toolchain@master
with:
toolchain: 1.89.0
toolchain: 1.95.0
- name: cargo +1.89.0 check
- name: cargo +1.95.0 check
run: cargo check
+106
View File
@@ -5,6 +5,112 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## v0.7.2 (2026-04-20)
### Feat
- Created a separate 'ssl' property for the config so users don't have to specify an ssl_cert_path to use SSL or use the uri workaround for HTTPS API access
## v0.7.1 (2026-02-04)
### Feat
- Added support for a system-wide notification popup mechanism that works across Servarrs
- Implemented a 'config-path' command to print out the default Managarr configuration file path to help address #54
- Full support for filtering disks and aggregating root folders in the UI's 'Stats' block
- proper collapsing of root folder paths in the stats layer of the UI
- Added config option to filter for specific disk space paths to display in the UI (CLI is unaffected)
- Improved disk-space UI and CLI that shows the actual path being monitored instead of just a disk number
- Implemented the forgotten lidarr list disk-space command
### Fix
- Improved the system notification feature so it can persist between modals
- Sonarr API updated to somtimes allow either seeders or leechers to be null
- Improved the first-time run behavior so that it outputs the default configuration file it tries to load to help users locate the file on first-runs
- 'managarr config-path' should work without a pre-existing config already in place [#54]
### Refactor
- Removed the filtering of monitored_storage_paths from the networking module and migrated all of it to the UI
## v0.7.0 (2026-01-21)
### Feat
- Blocklist support in Lidarr in both the CLI and TUI
- CLI and TUI support for track history and track details in Lidarr
- Lidarr UI support for album details popup
- Implemented TUI handler support for the Album Details popup in Lidarr
- Bulk added CLI support for tracks and album functionalities in Lidarr
- Implemented the manual artist discography search tab in Lidarr's artist details UI
- Lidarr CLI support for downloading a release
- CLI support for searching for discography releases in Lidarr
- Added TUI and CLI support for viewing Artist history in Lidarr
- Full Lidarr system support for both the CLI and TUI
- Full CLI and TUI support for the Lidarr Indexers tab
- Full support for adding a root folder in Lidarr from both the CLI and TUI
- naive lidarr root folder tab implementation. Needs improved add logic
- Downloads tab support in Lidarr
- Created a History tab in the Radarr UI and created a list history command and mark-history-item-as-failed command for Radarr
- Implemented the Lidarr History tab and CLI support
- TUI support for deleting a Lidarr album from the artist details popup
- CLI support for deleting an album from Lidarr
- Completed support for viewing Lidarr artist details
- Full CLI and TUI support for adding an artist to Lidarr
- Include the Lidarr artist disambiguation in the title of the Edit Artist popup
- Initial Lidarr support for searching for new artists
- Lidarr CLI commands to list quality profiles and metadata profiles
- Improved CLI readability by creating a separate Global Options section for global flags
- CLI support for deleting a tag in Lidarr
- Lidarr CLI support for listing and adding tags
- Added CLI and TUI support for editing Lidarr artists
- Support for updating all Lidarr artists in both the CLI and TUI
- Added Lidarr CLI support for fetching the host config and the security config
- Created Lidarr commands: 'get artist-details' and 'get system-status'
- Fetch the artist members as part of the artist details query
- Support for toggling the monitoring of a given artist via the CLI and TUI
- Full support for deleting an artist via CLI and TUI
- TUI support for Lidarr library
- CLI support for listing artists
- Improved UI speed and responsiveness
### Fix
- Sonarr network wasn't checking for the user to be using the sorting block when populating season details
- Sonarr CLI was not properly filtering out episode and season releases when manually searching for releases
- Sonarr manual search TUI and CLI incorrectly displaying the same unfiltered results for both season and episode searches
- Slowed down the automatic text scrolling in tables so the text is readable
- Expanded the history item details size so that it can include all the available information for a given item; was previously being cut off on some screens
- Bug in submitting the update series prompt in the series details UI in Sonarr
- Don't include Lidarr artist disambiguation in Edit popup title when it is empty
- Refactored how quality profiles, language profiles, and metadata profiles are populated for each servarr so they sort using the ID to mimic the web UI better
- Added the correct keybinding context to the Lidarr edit artist popup
- Improved fault tolerance for search result tables and test all indexer results tables
- Prevented additional empty slice errors in indexer tables
- Fixed a bug in all Servarr implementations to not try to get the current selection of a search table when an error is returned from the API
- Fixed an issue with the Managarr table that would incorrectly try to display things before is_loading was ready
- Fixed a bug where the edit collection popup would not display when opening it from collection details
### Refactor
- Refactored the SonarrEvent enum to not unnecessarily wrap dual series_id and season_number values in a tuple when both values can be passed directly
- Improved and simplified the implementation of history details for both Sonarr and Lidarr
- Let serde serialize Add Series and Add Movie enums instead of calling to_string up front
- Use is_multiple_of for the tick counter in the UI module
- Updated all model tests to use purpose-built assertions to improve readability and maintainability
- Updated all handler tests to use purpose built assertions to improve readability and maintainability
- Used is_multiple_of to make life easier and cleaner in the app module
- Refactored all cli tests to use purpose-built assertions
- Improved test assertions in the app module
- Created dedicated proptests and assertions to clean up the handler unit tests
- Migrated the handle_table_events macro into a trait for better IDE support, created a TableEventAdapter wrapper for the KeyEventHandlers to make it so that the trait can be used properly and a simple function to replace the previous call to the handle_table_events macro
- Simplified both the table_handler macro and the stateful_table implementation
- Improved error handling for the tail-logs subcommand to propagate errors up the stack instead of exiting there.
- Added accessor methods to servarr_data structs, replaced for loops with functional iterator chains, eliminated mutable state tracking, and updated network module to use get_or_insert_default() for modal options
- Improved error handling project-wide and cleaned up some regexes with unnecessary escapes (tail_logs and interpolate_env_vars)
- Refactored to use more idiomatic let-else statements where applicable
## v0.6.3 (2025-12-13)
### Fix
+7
View File
@@ -91,5 +91,12 @@ Then, you can run workflows locally without having to commit and see if the GitH
act -W .github/workflows/release.yml --input_type bump=minor
```
## Authorship Policy
All code in this repository is written and reviewed by humans. AI-generated code (e.g., Copilot, ChatGPT,
Claude, etc.) is not permitted unless explicitly disclosed and approved.
Submissions must certify that the contributor understands and can maintain the code they submit.
## Questions? Reach out to me!
If you encounter any questions while developing Managarr, please don't hesitate to reach out to me at alex.j.tusa@gmail.com. I'm happy to help contributors, new and experienced in any way I can!
Generated
+1002 -733
View File
File diff suppressed because it is too large Load Diff
+36 -36
View File
@@ -1,6 +1,6 @@
[package]
name = "managarr"
version = "0.6.3"
version = "0.7.2"
authors = ["Alex Clarke <alex.j.tusa@gmail.com>"]
description = "A TUI and CLI to manage your Servarrs"
keywords = ["managarr", "ratatui", "dashboard", "servarr", "tui"]
@@ -10,7 +10,7 @@ homepage = "https://github.com/Dark-Alex-17/managarr"
readme = "README.md"
edition = "2024"
license = "MIT"
rust-version = "1.89.0"
rust-version = "1.95.0"
exclude = [".github", "CONTRIBUTING.md", "*.log", "tags"]
[workspace]
@@ -20,67 +20,67 @@ members = [
]
[dependencies]
anyhow = "1.0.68"
backtrace = "0.3.74"
anyhow = "1.0.100"
backtrace = "0.3.76"
bimap = { version = "0.6.3", features = ["serde"] }
chrono = { version = "0.4.38", features = ["serde"] }
confy = { version = "0.6.0", default-features = false, features = [
chrono = { version = "0.4.43", features = ["serde"] }
confy = { version = "2.0.0", default-features = false, features = [
"yaml_conf",
] }
crossterm = "0.28.1"
derivative = "2.2.0"
human-panic = "2.0.2"
indoc = "2.0.0"
log = "0.4.17"
log4rs = { version = "1.2.0", features = ["file_appender"] }
regex = "1.11.1"
reqwest = { version = "0.12.9", features = ["json"] }
serde_yaml = "0.9.16"
serde_json = "1.0.91"
serde = { version = "1.0.214", features = ["derive"] }
human-panic = "2.0.6"
indoc = "2.0.7"
log = "0.4.29"
log4rs = { version = "1.4.0", features = ["rolling_file_appender", "compound_policy", "size_trigger", "fixed_window_roller"] }
regex = "1.12.2"
reqwest = { version = "0.13.2", features = ["json"] }
serde_yaml = "0.9.34"
serde_json = "1.0.149"
serde = { version = "1.0.228", features = ["derive"] }
strum = { version = "0.26.3", features = ["derive"] }
strum_macros = "0.26.4"
tokio = { version = "1.44.2", features = ["full"] }
tokio-util = "0.7.8"
tokio = { version = "1.49.0", features = ["full"] }
tokio-util = "0.7.18"
ratatui = { version = "0.30.0", features = [
"all-widgets",
"unstable-widget-ref",
] }
urlencoding = "2.1.2"
clap = { version = "4.5.20", features = [
urlencoding = "2.1.3"
clap = { version = "4.5.56", features = [
"derive",
"cargo",
"env",
"wrap_help",
] }
clap_complete = "4.5.33"
clap_complete = "4.5.65"
itertools = "0.14.0"
ctrlc = "3.4.5"
colored = "3.0.0"
async-trait = "0.1.83"
ctrlc = "3.5.1"
colored = "3.1.1"
async-trait = "0.1.89"
dirs-next = "2.0.0"
managarr-tree-widget = "0.25.0"
indicatif = "0.17.9"
derive_setters = "0.1.6"
deunicode = "1.6.0"
openssl = { version = "0.10.70", features = ["vendored"] }
indicatif = "0.17.11"
derive_setters = "0.1.9"
deunicode = "1.6.2"
openssl = { version = "0.10.79", features = ["vendored"] }
veil = "0.2.0"
validate_theme_derive = "0.1.0"
enum_display_style_derive = "0.1.0"
[dev-dependencies]
assert_cmd = "2.0.16"
mockall = "0.13.0"
mockito = "1.0.0"
pretty_assertions = "1.3.0"
proptest = "1.6.0"
assert_cmd = "2.1.2"
mockall = "0.13.1"
mockito = "1.7.1"
pretty_assertions = "1.4.1"
proptest = "1.9.0"
rstest = "0.25.0"
serial_test = "3.2.0"
assertables = "9.8.2"
insta = "1.41.1"
serial_test = "3.3.1"
assertables = "9.8.4"
insta = "1.46.1"
[dev-dependencies.cargo-husky]
version = "1"
version = "1.5.0"
default-features = false
features = ["user-hooks"]
+2
View File
@@ -21,6 +21,8 @@ RUN mv target/release/managarr .
FROM debian:stable-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
# Copy the compiled binary from the builder container
COPY --from=builder --chown=nonroot:nonroot /usr/src/managarr-temp/managarr /usr/local/bin
+187 -65
View File
@@ -3,7 +3,6 @@
![Check](https://github.com/Dark-Alex-17/managarr/actions/workflows/check.yml/badge.svg)
![Test](https://github.com/Dark-Alex-17/managarr/actions/workflows/test.yml/badge.svg)
![License](https://img.shields.io/badge/license-MIT-blueviolet.svg)
![LOC](https://tokei.rs/b1/github/Dark-Alex-17/managarr?category=code)
[![crates.io link](https://img.shields.io/crates/v/managarr.svg)](https://crates.io/crates/managarr)
![Release](https://img.shields.io/github/v/release/Dark-Alex-17/managarr?color=%23c694ff)
[![codecov](https://codecov.io/gh/Dark-Alex-17/managarr/graph/badge.svg?token=33G179TW67)](https://codecov.io/gh/Dark-Alex-17/managarr)
@@ -12,17 +11,16 @@
![Docker pulls](https://img.shields.io/docker/pulls/darkalex17/managarr?label=Docker%20downloads)
[![Matrix](https://img.shields.io/matrix/managarr-room%3Amatrix.org?logo=matrix&server_fqdn=matrix.org&fetchMode=guest&style=social&label=Managarr%20Matrix%20Space&link=https%3A%2F%2Fmatrix.to%2F%23%2F%23managarr%3Amatrix.org)](https://matrix.to/#/#managarr:matrix.org)
Managarr is a TUI and CLI to help you manage your HTPC (Home Theater PC). Built with 🤎 in Rust!
![library](screenshots/sonarr/sonarr_library.png)
![library](screenshots/lidarr/lidarr_library.png)
## What Servarrs are supported?
- [x] ![radarr_logo](logos/radarr.png) [Radarr](https://wiki.servarr.com/radarr)
- [x] ![sonarr_logo](logos/sonarr.png) [Sonarr](https://wiki.servarr.com/en/sonarr)
- [x] ![lidarr_logo](logos/lidarr.png) [Lidarr](https://wiki.servarr.com/en/lidarr)
- [ ] ![readarr_logo](logos/readarr.png) [Readarr](https://wiki.servarr.com/en/readarr)
- [ ] ![lidarr_logo](logos/lidarr.png) [Lidarr](https://wiki.servarr.com/en/lidarr)
- [ ] ![prowlarr_logo](logos/prowlarr.png) [Prowlarr](https://wiki.servarr.com/en/prowlarr)
- [ ] ![whisparr_logo](logos/whisparr.png) [Whisparr](https://wiki.servarr.com/whisparr)
- [ ] ![bazarr_logo](logos/bazarr.png) [Bazarr](https://www.bazarr.media/)
@@ -56,9 +54,9 @@ Run Managarr as a docker container by mounting your `config.yml` file to `/root/
docker run --rm -it -v /home/aclarke/.config/managarr/config.yml:/root/.config/managarr/config.yml darkalex17/managarr:latest
```
You can also clone this repo and run `make docker` to build a docker image locally and run it using the above command.
You can also clone this repo and run `just build-docker` to build a docker image locally and run it using the above command.
Please note that you will need to create and popular your configuration file first before starting the container. Otherwise, the container will fail to start.
Please note that you will need to create and populate your configuration file first before starting the container. Otherwise, the container will fail to start.
**Note:** If you run into errors using relative file paths when mounting the volume with the configuration file, try using an absolute path.
@@ -96,7 +94,7 @@ of Chocolatey packages take quite some time, and thus the package may not be ava
choco install managarr
# Some newer releases may require a version number, so you can specify it like so:
choco install managarr --version=0.5.0
choco install managarr --version=0.7.0
```
To upgrade to the latest and greatest version of Managarr:
@@ -104,7 +102,7 @@ To upgrade to the latest and greatest version of Managarr:
choco upgrade managarr
# To upgrade to a specific version:
choco upgrade managarr --version=0.5.0
choco upgrade managarr --version=0.7.0
```
### Manual
@@ -182,14 +180,30 @@ Key:
| ✅ | ✅ | View and browse logs, tasks, events queues, and updates |
| ✅ | ✅ | Manually trigger scheduled tasks |
### Lidarr
| TUI | CLI | Feature |
|-----|-----|----------------------------------------------------------------------------------------------------------------|
| ✅ | ✅ | View your library, downloads, blocklist, tracks |
| ✅ | ✅ | View details of a specific artists, albums, or tracks including description, history, downloaded file info |
| 🚫 | ✅ | View your host and security configs from the CLI to programmatically fetch the API token, among other settings |
| ✅ | ✅ | Search your library |
| ✅ | ✅ | Add artists to your library |
| ✅ | ✅ | Delete artists, downloads, indexers, root folders, and track files |
| ✅ | ✅ | Trigger automatic searches for artists or albums |
| ✅ | ✅ | Trigger refresh and disk scan for artists and downloads |
| ✅ | ✅ | Manually search for full artist discographies or albums |
| ✅ | ✅ | Edit your artists and indexers |
| ✅ | ✅ | Manage your tags |
| ✅ | ✅ | Manage your root folders |
| ✅ | ✅ | Manage your blocklist |
| ✅ | ✅ | View and browse logs, tasks, events queues, and updates |
| ✅ | ✅ | Manually trigger scheduled tasks |
### Readarr
- [ ] Support for Readarr
### Lidarr
- [ ] Support for Lidarr
### Whisparr
- [ ] Support for Whisparr
@@ -231,7 +245,7 @@ To see all available commands, simply run `managarr --help`:
```shell
$ managarr --help
managarr 0.5.1
managarr 0.7.0
Alex Clarke <alex.j.tusa@gmail.com>
A TUI and CLI to manage your Servarrs
@@ -241,20 +255,35 @@ Usage: managarr [OPTIONS] [COMMAND]
Commands:
radarr Commands for manging your Radarr instance
sonarr Commands for manging your Sonarr instance
lidarr Commands for manging your Lidarr instance
completions Generate shell completions for the Managarr CLI
tail-logs Tail Managarr logs
config-path Print the full path to the default configuration file.
This file can be changed to another location using the '--config-file' flag
help Print this message or the help of the given subcommand(s)
Options:
--disable-spinner Disable the spinner (can sometimes make parsing output challenging) [env: MANAGARR_DISABLE_SPINNER=]
--config-file <CONFIG_FILE> The Managarr configuration file to use [env: MANAGARR_CONFIG_FILE=]
--themes-file <THEMES_FILE> The Managarr themes file to use [env: MANAGARR_THEMES_FILE=]
--theme <THEME> The name of the Managarr theme to use [env: MANAGARR_THEME=]
--servarr-name <SERVARR_NAME> For multi-instance configurations, you need to specify the name of the instance configuration that you want to use.
This is useful when you have multiple instances of the same Servarr defined in your config file.
By default, if left empty, the first configured Servarr instance listed in the config file will be used.
-h, --help Print help
-V, --version Print version
-h, --help Print help
-V, --version Print version
Global Options:
--disable-spinner Disable the spinner (can sometimes make parsing output
challenging) [env: MANAGARR_DISABLE_SPINNER=]
--config-file <CONFIG_FILE> The Managarr configuration file to use; defaults to the
path shown by 'managarr config-path' [env:
MANAGARR_CONFIG_FILE=]
--themes-file <THEMES_FILE> The Managarr themes file to use [env:
MANAGARR_THEMES_FILE=]
--theme <THEME> The name of the Managarr theme to use [env:
MANAGARR_THEME=]
--servarr-name <SERVARR_NAME> For multi-instance configurations, you need to specify
the name of the instance configuration that you want to
use.
This is useful when you have multiple instances of the
same Servarr defined in your config file.
By default, if left empty, the first configured Servarr
instance listed in the config file will be used.
```
All subcommands also have detailed help menus to show you how to use them. For example, to see all available commands for Sonarr, you would run:
@@ -283,12 +312,21 @@ Commands:
test-all-indexers Test all Sonarr indexers
toggle-episode-monitoring Toggle monitoring for the specified episode
toggle-season-monitoring Toggle monitoring for the specified season that corresponds to the specified series ID
toggle-series-monitoring Toggle monitoring for the specified series corresponding to the given series ID
help Print this message or the help of the given subcommand(s)
Options:
--disable-spinner Disable the spinner (can sometimes make parsing output challenging) [env: MANAGARR_DISABLE_SPINNER=]
--config <CONFIG> The Managarr configuration file to use [env: MANAGARR_CONFIG_FILE=]
-h, --help Print help
-h, --help Print help
Global Options:
--disable-spinner Disable the spinner (can sometimes make parsing output challenging) [env: MANAGARR_DISABLE_SPINNER=]
--config-file <CONFIG_FILE> The Managarr configuration file to use [env: MANAGARR_CONFIG_FILE=]
--themes-file <THEMES_FILE> The Managarr themes file to use [env: MANAGARR_THEMES_FILE=]
--theme <THEME> The name of the Managarr theme to use [env: MANAGARR_THEME=]
--servarr-name <SERVARR_NAME> For multi-instance configurations, you need to specify the name of the instance configuration that you want to use.
This is useful when you have multiple instances of the same Servarr defined in your config file.
By default, if left empty, the first configured Servarr instance listed in the config file will be used.
```
**Pro Tip:** The CLI is even more powerful and useful when used in conjunction with the `jq` CLI tool. This allows you to parse the JSON response from the Managarr CLI and use it in your scripts; For example, to extract the `movieId` of the movie "Ad Astra", you would run:
@@ -300,23 +338,44 @@ $ managarr radarr list movies | jq '.[] | select(.title == "Ad Astra") | .id'
# Configuration
Managarr assumes reasonable defaults to connect to each service (i.e. Radarr is on localhost:7878),
but all servers will require you to input the API token.
but all servers will require you to input the API token. This means that for each Servarr you configure,
if you define only the `api_token`, Managarr will assume the Servarr is running on `localhost` and on the
default port for that respective service. That is:
The configuration file is located somewhere different for each OS.
| Servarr | Default Host | Default Port |
|---------|--------------|--------------|
| Radarr | `localhost` | 7878 |
| Sonarr | `localhost` | 8989 |
| Lidarr | `localhost` | 8686 |
### Linux
```
$HOME/.config/managarr/config.yml
> [!TIP]
> In general, all Servarrs store their API tokens under Settings -> General -> Security -> API Key in their web UIs.
## Minimum Configuration Requirements
The following configuration file will connect to each Servarr running on localhost with their default ports. The only
requirement for each is the specification of an API token.
```yaml
radarr:
# Connect to Radarr running on localhost:7878
- api_token: <your-radarr-api-token-here>
sonarr:
# Connect to sonarr running on localhost:8989
- api_token: <your-sonarr-api-token-here>
lidarr:
# Connect to lidarr running on localhost:8686
- api_token: <your-lidarr-api-token-here>
```
### Mac
```
$HOME/Library/Application Support/managarr/config.yml
```
## Configuration File Location
### Windows
```
%APPDATA%/Roaming/managarr/config.yml
The configuration file is located somewhere different for each OS, so run the following command to print out the default
location of the `managarr` configuration file for your system:
```shell
managarr config-path
```
## Specify Which Configuration File to Use
@@ -335,43 +394,102 @@ radarr:
- host: 192.168.0.78
port: 7878
api_token: someApiToken1234567890
ssl_cert_path: /path/to/radarr.crt # Required to enable SSL
sonarr:
- uri: http://htpc.local/sonarr # Example of using the 'uri' key instead of 'host' and 'port'
ssl_cert_path: /path/to/radarr.crt # Use the specified SSL certificate to connect to this Servarr
# Enables SSL regardless of the value of the 'ssl'
# See the SSL Configuration section below for more information
- host: 192.168.0.79
port: 7878
api_token: someApiToken1234567890
ssl: true # Use SSL to connect to this Servarr
# This will assume that you have the SSL certificate installed to your system trust store
# See the SSL Configuration section below for more information
- uri: http://htpc.local/radarr # Example of using the 'uri' key instead of 'host' and 'port'
api_token: someApiToken1234567890
sonarr:
- host: 192.168.0.89
port: 8989
api_token_file: /root/.config/sonarr_api_token # Example of loading the API token from a file instead of hardcoding it in the configuration file
- name: Anime Sonarr # An example of a custom name for a secondary Sonarr instance
host: 192.168.0.89
host: 192.168.1.89
port: 8989
api_token: someApiToken1234567890
readarr:
- host: 192.168.0.87
port: 8787
api_token_file: /root/.config/readarr_api_token # Example of loading the API token from a file instead of hardcoding it in the configuration file
lidarr:
- host: 192.168.0.86
port: 8686
api_token: ${MY_LIDARR_API_TOKEN} # Example of configuring using environment variables
whisparr:
- host: 192.168.0.69
port: 6969
monitored_storage_paths: # Filter which Root Folders or Disk Storage you want displayed in the UI's 'Stats' block
# Note: Setting these values does not affect what shows up in the 'Root Folders' tab of the UI.
- /nfs # An example disk (i.e. '<servarr> list disk-space' command) you want displayed in the UI under 'Storage:'
- /media # An example root folder you want displayed in the UI
# Root folders collapse up to the super-directory to reduce duplication in the UI. For example:
# if you have root folders '/media/tv', '/media/cartoons' and '/media/reality', and you set this
# monitored path, the UI will show '/media/[tv,cartoons,reality]' under Root Folders
- host: 192.168.1.86
port: 8686
api_token: someApiToken1234567890
ssl_cert_path: /path/to/whisparr.crt
ssl_cert_path: /path/to/lidarr_1.crt
custom_headers: # Example of adding custom headers to all requests to the Servarr instance
traefik-auth-bypass-key: someBypassKey1234567890
SOME-OTHER-CUSTOM-HEADER: ${MY_CUSTOM_HEADER_VALUE}
bazarr:
- host: 192.168.0.67
port: 6767
api_token: someApiToken1234567890
prowlarr:
- host: 192.168.0.96
port: 9696
api_token: someApiToken1234567890
tautulli:
- host: 192.168.0.81
port: 8181
api_token: someApiToken1234567890
```
### SSL Configuration
If your Servarr is using SSL or self-signed certificates, you may need to specify additional configuration options to connect without issues.
**If your Servarr's domain CA is installed in the system's trust store:**
Then you can simply specify `ssl: true` and Managarr will be able to connect to your Servarr:
```yaml
radarr:
- host: 192.168.0.78
port: 7878
api_token: yourApiTokenHere
ssl: true
```
**If your Servarr's domain CA is not installed:**
You'll either need to specify the path to the certificate via the `ssl_cert_path` property, or you'll need to install the certificate into your system store.
To acquire the cert for your Servarr's domain, you can use the following command:
```shell
openssl s_client -show-certs -connect <your-servarr-domain.com>:<port> </dev/null |\
sed -n -e '/-.BEGIN/,/-.END/ p' > /path/to/your/servarr.pem
```
Now, you can either specify `ssl_cert_path: /path/to/your/servarr.pem`:
Example configuration with a certificate that's not installed to the system trust store:
```yaml
radarr:
- host: 192.168.0.78
port: 7878
api_token: yourApiTokenHere
ssl_cert_path: /path/to/your/certificate.crt
```
Or install the certificate into your system's trust store.
For example, if you're on a Debian-based system and have `ca-certificates` installed (`sudo apt install ca-certificates`):
```shell
sudo mv /path/to/your/servarr.pem /usr/local/share/ca-certificates/servarr.pem
sudo update-ca-certificates
```
Example configuration with a certificate that is installed to the system trust store:
```yaml
radarr:
- host: 192.168.0.78
port: 7878
api_token: yourApiTokenHere
ssl: true
```
### Example Multi-Instance Configuration:
@@ -428,9 +546,6 @@ Managarr supports using environment variables on startup so you don't have to al
| `MANAGARR_CONFIG_FILE` | Set the path to the config file | `--config` |
| `MANAGARR_DISABLE_SPINNER` | Disable the CLI spinner (this can be useful when scripting and parsing output) | `--disable-spinner` |
## Track What I'm Currently Working On
To see what feature(s) I'm currently working on, check out my [Wekan Board](https://wekan.alexjclarke.com/b/dHoGjBb44MHM9HSv4/managarr).
## Screenshots
### Radarr
@@ -446,6 +561,13 @@ To see what feature(s) I'm currently working on, check out my [Wekan Board](http
![season_details](screenshots/sonarr/season_details.png)
![manual_episode_search](screenshots/sonarr/manual_episode_search.png)
### Lidarr
![lidarr_library](screenshots/lidarr/lidarr_library.png)
![artist_details](screenshots/lidarr/artist_details.png)
![album_details](screenshots/lidarr/album_details.png)
![artist_discography_search](screenshots/lidarr/artist_discography_search.png)
![manual_album_search](screenshots/lidarr/manual_album_search.png)
### General
![logs](screenshots/radarr/logs.png)
![indexers](screenshots/radarr/indexers.png)
@@ -461,8 +583,8 @@ To see what feature(s) I'm currently working on, check out my [Wekan Board](http
## Servarr Requirements
* [Radarr >= 5.3.6.8612](https://radarr.video/docs/api/)
* [Sonarr >= v4](https://sonarr.tv/docs/api/)
* [Readarr v1](https://readarr.com/docs/api/)
* [Lidarr v1](https://lidarr.audio/docs/api/)
* [Readarr v1](https://readarr.com/docs/api/)
* [Whisparr >= v3](https://whisparr.com/docs/api/)
* [Prowlarr v1](https://prowlarr.com/docs/api/)
* [Bazarr v1.1.4](http://localhost:6767/api)
+2 -4
View File
@@ -1,7 +1,5 @@
VERSION := "latest"
IMG_NAME := "darkalex17/managarr"
IMAGE := "{{IMG_NAME}}:{{VERSION}}"
# List all recipes
default:
@@ -87,5 +85,5 @@ build build_type='debug':
# Build the docker image
[group: 'build']
build-docker:
@DOCKER_BUILDKIT=1 docker build --rm -t {{IMAGE}}
build-docker version=VERSION:
@DOCKER_BUILDKIT=1 docker build --rm -t {{IMG_NAME}}:{{version}} .
+1 -1
View File
@@ -1,5 +1,5 @@
tab_spaces=2
edition = "2021"
edition = "2024"
reorder_imports = true
imports_granularity = "Crate"
group_imports = "StdExternalCrate"
Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 252 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 319 KiB

+126 -1
View File
@@ -447,6 +447,78 @@ mod tests {
assert_none!(config.port);
}
#[test]
#[serial]
fn test_deserialize_optional_env_var_bool_is_bool() {
let yaml_data = r#"
host: localhost
api_token: "test123"
ssl: true
"#;
let config: ServarrConfig = serde_yaml::from_str(yaml_data).unwrap();
assert_some_eq_x!(&config.ssl, &true);
}
#[test]
#[serial]
fn test_deserialize_optional_env_var_bool_is_string() {
let yaml_data = r#"
host: localhost
api_token: "test123"
ssl: "true"
"#;
let config: ServarrConfig = serde_yaml::from_str(yaml_data).unwrap();
assert_some_eq_x!(&config.ssl, &true);
}
#[test]
#[serial]
fn test_deserialize_optional_env_var_bool_is_present() {
unsafe { std::env::set_var("TEST_VAR_DESERIALIZE_OPTION_BOOL", "true") };
let yaml_data = r#"
host: localhost
api_token: "test123"
ssl: ${TEST_VAR_DESERIALIZE_OPTION_BOOL}
"#;
let config: ServarrConfig = serde_yaml::from_str(yaml_data).unwrap();
assert_some_eq_x!(&config.ssl, &true);
unsafe { std::env::remove_var("TEST_VAR_DESERIALIZE_OPTION_BOOL") };
}
#[test]
#[serial]
fn test_deserialize_optional_env_var_bool_defaults_to_false() {
unsafe { std::env::set_var("TEST_VAR_DESERIALIZE_OPTION_BOOL_FALSEY", "test") };
let yaml_data = r#"
host: localhost
api_token: "test123"
ssl: ${TEST_VAR_DESERIALIZE_OPTION_BOOL_FALSEY}
"#;
let config: ServarrConfig = serde_yaml::from_str(yaml_data).unwrap();
assert_some_eq_x!(&config.ssl, &false);
unsafe { std::env::remove_var("TEST_VAR_DESERIALIZE_OPTION_BOOL_FALSEY") };
}
#[test]
fn test_deserialize_optional_env_var_bool_empty() {
let yaml_data = r#"
host: localhost
api_token: "test123"
"#;
let config: ServarrConfig = serde_yaml::from_str(yaml_data).unwrap();
assert_none!(config.ssl);
}
#[test]
#[serial]
fn test_deserialize_optional_env_var_header_map_is_present() {
@@ -507,6 +579,56 @@ mod tests {
assert_none!(config.custom_headers);
}
#[test]
#[serial]
fn test_deserialize_optional_env_var_string_vec_is_present() {
unsafe { std::env::set_var("TEST_VAR_DESERIALIZE_STRING_VEC_OPTION", "/path1") };
let expected_monitored_paths = ["/path1", "/path2"];
let yaml_data = r#"
monitored_storage_paths:
- ${TEST_VAR_DESERIALIZE_STRING_VEC_OPTION}
- /path2
"#;
let config: ServarrConfig = serde_yaml::from_str(yaml_data).unwrap();
assert_some_eq_x!(&config.monitored_storage_paths, &expected_monitored_paths);
unsafe { std::env::remove_var("TEST_VAR_DESERIALIZE_STRING_VEC_OPTION") };
}
#[test]
#[serial]
fn test_deserialize_optional_env_var_string_vec_does_not_overwrite_non_env_value() {
unsafe {
std::env::set_var(
"TEST_VAR_DESERIALIZE_STRING_VEC_OPTION_NO_OVERWRITE",
"/path3",
)
};
let expected_monitored_paths = ["/path1", "/path2"];
let yaml_data = r#"
monitored_storage_paths:
- /path1
- /path2
"#;
let config: ServarrConfig = serde_yaml::from_str(yaml_data).unwrap();
assert_some_eq_x!(&config.monitored_storage_paths, &expected_monitored_paths);
unsafe { std::env::remove_var("TEST_VAR_DESERIALIZE_STRING_VEC_OPTION_NO_OVERWRITE") };
}
#[test]
fn test_deserialize_optional_env_var_string_vec_empty() {
let yaml_data = r#"
api_token: "test123"
"#;
let config: ServarrConfig = serde_yaml::from_str(yaml_data).unwrap();
assert_none!(config.monitored_storage_paths);
}
#[test]
#[serial]
fn test_deserialize_optional_u16_env_var_is_present() {
@@ -620,10 +742,11 @@ mod tests {
let api_token = "thisisatest".to_owned();
let api_token_file = "/root/.config/api_token".to_owned();
let ssl_cert_path = "/some/path".to_owned();
let monitored_storage = vec!["/path1".to_owned(), "/path2".to_owned()];
let mut custom_headers = HeaderMap::new();
custom_headers.insert("X-Custom-Header", "value".parse().unwrap());
let expected_str = format!(
"ServarrConfig {{ name: Some(\"{name}\"), host: Some(\"{host}\"), port: Some({port}), uri: Some(\"{uri}\"), weight: Some({weight}), api_token: Some(\"***********\"), api_token_file: Some(\"{api_token_file}\"), ssl_cert_path: Some(\"{ssl_cert_path}\"), custom_headers: Some({{\"x-custom-header\": \"value\"}}) }}"
"ServarrConfig {{ name: Some(\"{name}\"), host: Some(\"{host}\"), port: Some({port}), uri: Some(\"{uri}\"), weight: Some({weight}), api_token: Some(\"***********\"), api_token_file: Some(\"{api_token_file}\"), ssl: Some(true), ssl_cert_path: Some(\"{ssl_cert_path}\"), custom_headers: Some({{\"x-custom-header\": \"value\"}}), monitored_storage_paths: Some([\"/path1\", \"/path2\"]) }}"
);
let servarr_config = ServarrConfig {
name: Some(name),
@@ -634,7 +757,9 @@ mod tests {
api_token: Some(api_token),
api_token_file: Some(api_token_file),
ssl_cert_path: Some(ssl_cert_path),
ssl: Some(true),
custom_headers: Some(custom_headers),
monitored_storage_paths: Some(monitored_storage),
};
assert_str_eq!(format!("{servarr_config:?}"), expected_str);
+18
View File
@@ -57,6 +57,24 @@ mod tests {
assert_eq!(app.tick_count, 0);
}
#[tokio::test]
async fn test_dispatch_by_blocklist_block() {
let (tx, mut rx) = mpsc::channel::<NetworkEvent>(500);
let mut app = App::test_default();
app.data.lidarr_data.prompt_confirm = true;
app.data.lidarr_data.artists.set_items(vec![artist()]);
app.network_tx = Some(tx);
app
.dispatch_by_lidarr_block(&ActiveLidarrBlock::Blocklist)
.await;
assert!(app.is_loading);
assert_eq!(rx.recv().await.unwrap(), LidarrEvent::GetBlocklist.into());
assert!(!app.data.sonarr_data.prompt_confirm);
assert_eq!(app.tick_count, 0);
}
#[tokio::test]
async fn test_dispatch_by_artist_history_block() {
let (tx, mut rx) = mpsc::channel::<NetworkEvent>(500);
+5
View File
@@ -27,6 +27,11 @@ impl App<'_> {
.dispatch_network_event(LidarrEvent::ListArtists.into())
.await;
}
ActiveLidarrBlock::Blocklist => {
self
.dispatch_network_event(LidarrEvent::GetBlocklist.into())
.await;
}
ActiveLidarrBlock::Downloads => {
self
.dispatch_network_event(LidarrEvent::GetDownloads(500).into())
+54 -4
View File
@@ -13,6 +13,7 @@ use tokio_util::sync::CancellationToken;
use veil::Redact;
use crate::cli::Command;
use crate::models::servarr_data::Notification;
use crate::models::servarr_data::lidarr::lidarr_data::{ActiveLidarrBlock, LidarrData};
use crate::models::servarr_data::radarr::radarr_data::{ActiveRadarrBlock, RadarrData};
use crate::models::servarr_data::sonarr::sonarr_data::{ActiveSonarrBlock, SonarrData};
@@ -38,6 +39,7 @@ pub struct App<'a> {
pub server_tabs: TabState,
pub keymapping_table: Option<StatefulTable<KeybindingItem>>,
pub error: HorizontallyScrollableText,
pub notification: Option<Notification>,
pub tick_until_poll: u64,
pub ticks_until_scroll: u64,
pub tick_count: u64,
@@ -254,6 +256,7 @@ impl Default for App<'_> {
cancellation_token: CancellationToken::new(),
keymapping_table: None,
error: HorizontallyScrollableText::default(),
notification: None,
is_first_render: true,
server_tabs: TabState::new(Vec::new()),
tick_until_poll: 400,
@@ -346,11 +349,11 @@ pub struct AppConfig {
}
impl AppConfig {
pub fn validate(&self) {
pub fn validate(&self, config_path: &str) {
if self.lidarr.is_none() && self.radarr.is_none() && self.sonarr.is_none() {
log_and_print_error(
"No Servarr configuration provided in the specified configuration file".to_owned(),
);
log_and_print_error(format!(
"No Servarrs are configured in the file: {config_path}"
));
process::exit(1);
}
@@ -428,6 +431,8 @@ pub struct ServarrConfig {
pub api_token: Option<String>,
#[serde(default, deserialize_with = "deserialize_optional_env_var")]
pub api_token_file: Option<String>,
#[serde(default, deserialize_with = "deserialize_optional_env_var_bool")]
pub ssl: Option<bool>,
#[serde(default, deserialize_with = "deserialize_optional_env_var")]
pub ssl_cert_path: Option<String>,
#[serde(
@@ -436,6 +441,8 @@ pub struct ServarrConfig {
serialize_with = "serialize_header_map"
)]
pub custom_headers: Option<HeaderMap>,
#[serde(default, deserialize_with = "deserialize_optional_env_var_string_vec")]
pub monitored_storage_paths: Option<Vec<String>>,
}
impl ServarrConfig {
@@ -481,7 +488,9 @@ impl Default for ServarrConfig {
api_token: Some(String::new()),
api_token_file: None,
ssl_cert_path: None,
ssl: None,
custom_headers: None,
monitored_storage_paths: None,
}
}
}
@@ -526,6 +535,29 @@ where
}
}
fn deserialize_optional_env_var_bool<'de, D>(deserializer: D) -> Result<Option<bool>, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum StringOrBool {
Bool(bool),
String(String),
}
match StringOrBool::deserialize(deserializer)? {
StringOrBool::Bool(b) => Ok(Some(b)),
StringOrBool::String(s) => {
let val = interpolate_env_vars(&s)
.to_lowercase()
.parse()
.unwrap_or(false);
Ok(Some(val))
}
}
}
fn deserialize_optional_env_var_header_map<'de, D>(
deserializer: D,
) -> Result<Option<HeaderMap>, D::Error>
@@ -548,6 +580,24 @@ where
}
}
fn deserialize_optional_env_var_string_vec<'de, D>(
deserializer: D,
) -> Result<Option<Vec<String>>, D::Error>
where
D: serde::Deserializer<'de>,
{
let opt: Option<Vec<String>> = Option::deserialize(deserializer)?;
match opt {
Some(vec) => Ok(Some(
vec
.into_iter()
.map(|it| interpolate_env_vars(&it))
.collect(),
)),
None => Ok(None),
}
}
fn deserialize_u16_env_var<'de, D>(deserializer: D) -> Result<Option<u16>, D::Error>
where
D: serde::Deserializer<'de>,
+4 -6
View File
@@ -58,21 +58,19 @@ impl App<'_> {
}
ActiveSonarrBlock::SeasonHistory => {
if !self.data.sonarr_data.seasons.is_empty() {
let (series_id, season_number) = self.extract_series_id_season_number_tuple().await;
self
.dispatch_network_event(
SonarrEvent::GetSeasonHistory(self.extract_series_id_season_number_tuple().await)
.into(),
)
.dispatch_network_event(SonarrEvent::GetSeasonHistory(series_id, season_number).into())
.await;
}
}
ActiveSonarrBlock::ManualSeasonSearch => {
match self.data.sonarr_data.season_details_modal.as_ref() {
Some(season_details_modal) if season_details_modal.season_releases.is_empty() => {
let (series_id, season_number) = self.extract_series_id_season_number_tuple().await;
self
.dispatch_network_event(
SonarrEvent::GetSeasonReleases(self.extract_series_id_season_number_tuple().await)
.into(),
SonarrEvent::GetSeasonReleases(series_id, season_number).into(),
)
.await;
}
+2 -2
View File
@@ -132,7 +132,7 @@ mod tests {
assert!(app.is_loading);
assert_eq!(
sync_network_rx.recv().await.unwrap(),
SonarrEvent::GetSeasonHistory((1, 1)).into()
SonarrEvent::GetSeasonHistory(1, 1).into()
);
assert!(!app.data.sonarr_data.prompt_confirm);
assert_eq!(app.tick_count, 0);
@@ -175,7 +175,7 @@ mod tests {
assert!(app.is_loading);
assert_eq!(
sync_network_rx.recv().await.unwrap(),
SonarrEvent::GetSeasonReleases((1, 1)).into()
SonarrEvent::GetSeasonReleases(1, 1).into()
);
assert!(!app.data.sonarr_data.prompt_confirm);
assert_eq!(app.tick_count, 0);
+36 -1
View File
@@ -8,12 +8,18 @@ mod tests {
use serde_json::json;
use tokio::sync::Mutex;
use crate::cli::lidarr::LidarrCommand;
use crate::network::lidarr_network::LidarrEvent;
use crate::{
Cli,
app::App,
cli::{handle_command, mutex_flags_or_option, radarr::RadarrCommand, sonarr::SonarrCommand},
models::{
Serdeable,
lidarr_models::{
BlocklistItem as LidarrBlocklistItem, BlocklistResponse as LidarrBlocklistResponse,
LidarrSerdeable,
},
radarr_models::{
BlocklistItem as RadarrBlocklistItem, BlocklistResponse as RadarrBlocklistResponse,
RadarrSerdeable,
@@ -182,5 +188,34 @@ mod tests {
assert_ok!(&result);
}
// TODO: Implement test_cli_handler_delegates_lidarr_commands_to_the_lidarr_cli_handler
#[tokio::test]
async fn test_cli_handler_delegates_lidarr_commands_to_the_lidarr_cli_handler() {
let mut mock_network = MockNetworkTrait::new();
mock_network
.expect_handle_network_event()
.with(eq::<NetworkEvent>(LidarrEvent::GetBlocklist.into()))
.times(1)
.returning(|_| {
Ok(Serdeable::Lidarr(LidarrSerdeable::BlocklistResponse(
LidarrBlocklistResponse {
records: vec![LidarrBlocklistItem::default()],
},
)))
});
mock_network
.expect_handle_network_event()
.with(eq::<NetworkEvent>(LidarrEvent::ClearBlocklist.into()))
.times(1)
.returning(|_| {
Ok(Serdeable::Lidarr(LidarrSerdeable::Value(
json!({"testResponse": "response"}),
)))
});
let app_arc = Arc::new(Mutex::new(App::test_default()));
let clear_blocklist_command = LidarrCommand::ClearBlocklist.into();
let result = handle_command(&app_arc, clear_blocklist_command, &mut mock_network).await;
assert_ok!(&result);
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
use std::sync::Arc;
use anyhow::Result;
use clap::{ArgAction, Subcommand, arg};
use clap::{ArgAction, Subcommand};
use tokio::sync::Mutex;
use super::LidarrCommand;
+16
View File
@@ -28,6 +28,15 @@ pub enum LidarrDeleteCommand {
#[arg(long, help = "Add a list exclusion for this album")]
add_list_exclusion: bool,
},
#[command(about = "Delete the specified item from the Lidarr blocklist")]
BlocklistItem {
#[arg(
long,
help = "The ID of the blocklist item to remove from the blocklist",
required = true
)]
blocklist_item_id: i64,
},
#[command(about = "Delete the specified track file from disk")]
TrackFile {
#[arg(long, help = "The ID of the track file to delete", required = true)]
@@ -107,6 +116,13 @@ impl<'a, 'b> CliCommandHandler<'a, 'b, LidarrDeleteCommand> for LidarrDeleteComm
.await?;
serde_json::to_string_pretty(&resp)?
}
LidarrDeleteCommand::BlocklistItem { blocklist_item_id } => {
let resp = self
.network
.handle_network_event(LidarrEvent::DeleteBlocklistItem(blocklist_item_id).into())
.await?;
serde_json::to_string_pretty(&resp)?
}
LidarrDeleteCommand::TrackFile { track_file_id } => {
let resp = self
.network
@@ -86,6 +86,42 @@ mod tests {
assert_eq!(delete_command, expected_args);
}
#[test]
fn test_delete_blocklist_item_requires_arguments() {
let result =
Cli::command().try_get_matches_from(["managarr", "lidarr", "delete", "blocklist-item"]);
assert_err!(&result);
assert_eq!(
result.unwrap_err().kind(),
ErrorKind::MissingRequiredArgument
);
}
#[test]
fn test_delete_blocklist_item_success() {
let expected_args = LidarrDeleteCommand::BlocklistItem {
blocklist_item_id: 1,
};
let result = Cli::try_parse_from([
"managarr",
"lidarr",
"delete",
"blocklist-item",
"--blocklist-item-id",
"1",
]);
assert_ok!(&result);
let Some(Command::Lidarr(LidarrCommand::Delete(delete_command))) = result.unwrap().command
else {
panic!("Unexpected command type");
};
assert_eq!(delete_command, expected_args);
}
#[test]
fn test_delete_track_file_requires_arguments() {
let result =
@@ -361,6 +397,37 @@ mod tests {
assert_ok!(&result);
}
#[tokio::test]
async fn test_handle_delete_blocklist_item_command() {
let expected_blocklist_item_id = 1;
let mut mock_network = MockNetworkTrait::new();
mock_network
.expect_handle_network_event()
.with(eq::<NetworkEvent>(
LidarrEvent::DeleteBlocklistItem(expected_blocklist_item_id).into(),
))
.times(1)
.returning(|_| {
Ok(Serdeable::Lidarr(LidarrSerdeable::Value(
json!({"testResponse": "response"}),
)))
});
let app_arc = Arc::new(Mutex::new(App::test_default()));
let delete_blocklist_item_command = LidarrDeleteCommand::BlocklistItem {
blocklist_item_id: 1,
};
let result = LidarrDeleteCommandHandler::with(
&app_arc,
delete_blocklist_item_command,
&mut mock_network,
)
.handle()
.await;
assert_ok!(&result);
}
#[tokio::test]
async fn test_handle_delete_track_file_command() {
let expected_track_file_id = 1;
+37 -2
View File
@@ -25,7 +25,7 @@ mod tests {
#[rstest]
fn test_commands_that_have_no_arg_requirements(
#[values("test-all-indexers")] subcommand: &str,
#[values("clear-blocklist", "test-all-indexers")] subcommand: &str,
) {
let result = Cli::command().try_get_matches_from(["managarr", "lidarr", subcommand]);
@@ -284,7 +284,9 @@ mod tests {
use crate::cli::lidarr::manual_search_command_handler::LidarrManualSearchCommand;
use crate::cli::lidarr::refresh_command_handler::LidarrRefreshCommand;
use crate::cli::lidarr::trigger_automatic_search_command_handler::LidarrTriggerAutomaticSearchCommand;
use crate::models::lidarr_models::{LidarrReleaseDownloadBody, LidarrTaskName};
use crate::models::lidarr_models::{
BlocklistItem, BlocklistResponse, LidarrReleaseDownloadBody, LidarrTaskName,
};
use crate::models::servarr_models::IndexerSettings;
use crate::{
app::App,
@@ -546,6 +548,39 @@ mod tests {
assert_ok!(&result);
}
#[tokio::test]
async fn test_handle_clear_blocklist_command() {
let mut mock_network = MockNetworkTrait::new();
mock_network
.expect_handle_network_event()
.with(eq::<NetworkEvent>(LidarrEvent::GetBlocklist.into()))
.times(1)
.returning(|_| {
Ok(Serdeable::Lidarr(LidarrSerdeable::BlocklistResponse(
BlocklistResponse {
records: vec![BlocklistItem::default()],
},
)))
});
mock_network
.expect_handle_network_event()
.with(eq::<NetworkEvent>(LidarrEvent::ClearBlocklist.into()))
.times(1)
.returning(|_| {
Ok(Serdeable::Lidarr(LidarrSerdeable::Value(
json!({"testResponse": "response"}),
)))
});
let app_arc = Arc::new(Mutex::new(App::test_default()));
let claer_blocklist_command = LidarrCommand::ClearBlocklist;
let result = LidarrCliHandler::with(&app_arc, claer_blocklist_command, &mut mock_network)
.handle()
.await;
assert_ok!(&result);
}
#[tokio::test]
async fn test_download_release_command() {
let expected_release_download_body = LidarrReleaseDownloadBody {
+19 -1
View File
@@ -1,7 +1,7 @@
use std::sync::Arc;
use anyhow::Result;
use clap::{Subcommand, arg};
use clap::Subcommand;
use serde_json::json;
use tokio::sync::Mutex;
@@ -57,6 +57,10 @@ pub enum LidarrListCommand {
},
#[command(about = "List all artists in your Lidarr library")]
Artists,
#[command(about = "List all items in the Lidarr blocklist")]
Blocklist,
#[command(about = "List disk space details for all provisioned root folders in Lidarr")]
DiskSpace,
#[command(about = "List all active downloads in Lidarr")]
Downloads {
#[arg(long, help = "How many downloads to fetch", default_value_t = 500)]
@@ -200,6 +204,20 @@ impl<'a, 'b> CliCommandHandler<'a, 'b, LidarrListCommand> for LidarrListCommandH
.await?;
serde_json::to_string_pretty(&resp)?
}
LidarrListCommand::Blocklist => {
let resp = self
.network
.handle_network_event(LidarrEvent::GetBlocklist.into())
.await?;
serde_json::to_string_pretty(&resp)?
}
LidarrListCommand::DiskSpace => {
let resp = self
.network
.handle_network_event(LidarrEvent::GetDiskSpace.into())
.await?;
serde_json::to_string_pretty(&resp)?
}
LidarrListCommand::Downloads { count } => {
let resp = self
.network
@@ -27,6 +27,8 @@ mod tests {
fn test_list_commands_have_no_arg_requirements(
#[values(
"artists",
"blocklist",
"disk-space",
"indexers",
"metadata-profiles",
"quality-profiles",
@@ -433,6 +435,8 @@ mod tests {
#[rstest]
#[case(LidarrListCommand::Artists, LidarrEvent::ListArtists)]
#[case(LidarrListCommand::Blocklist, LidarrEvent::GetBlocklist)]
#[case(LidarrListCommand::DiskSpace, LidarrEvent::GetDiskSpace)]
#[case(LidarrListCommand::Indexers, LidarrEvent::GetIndexers)]
#[case(LidarrListCommand::MetadataProfiles, LidarrEvent::GetMetadataProfiles)]
#[case(LidarrListCommand::QualityProfiles, LidarrEvent::GetQualityProfiles)]
+14 -1
View File
@@ -2,7 +2,7 @@ use std::sync::Arc;
use add_command_handler::{LidarrAddCommand, LidarrAddCommandHandler};
use anyhow::Result;
use clap::{Subcommand, arg};
use clap::Subcommand;
use delete_command_handler::{LidarrDeleteCommand, LidarrDeleteCommandHandler};
use edit_command_handler::{LidarrEditCommand, LidarrEditCommandHandler};
use get_command_handler::{LidarrGetCommand, LidarrGetCommandHandler};
@@ -74,6 +74,8 @@ pub enum LidarrCommand {
about = "Commands to trigger automatic searches for releases of different resources in your Lidarr instance"
)]
TriggerAutomaticSearch(LidarrTriggerAutomaticSearchCommand),
#[command(about = "Clear the Lidarr blocklist")]
ClearBlocklist,
#[command(about = "Manually download the given release")]
DownloadRelease {
#[arg(long, help = "The GUID of the release to download", required = true)]
@@ -217,6 +219,17 @@ impl<'a, 'b> CliCommandHandler<'a, 'b, LidarrCommand> for LidarrCliHandler<'a, '
.handle()
.await?
}
LidarrCommand::ClearBlocklist => {
self
.network
.handle_network_event(LidarrEvent::GetBlocklist.into())
.await?;
let resp = self
.network
.handle_network_event(LidarrEvent::ClearBlocklist.into())
.await?;
serde_json::to_string_pretty(&resp)?
}
LidarrCommand::DownloadRelease { guid, indexer_id } => {
let params = LidarrReleaseDownloadBody { guid, indexer_id };
let resp = self
+8 -1
View File
@@ -1,8 +1,9 @@
use std::sync::Arc;
use anyhow::Result;
use clap::{Subcommand, command};
use clap::Subcommand;
use clap_complete::Shell;
use indoc::indoc;
use lidarr::{LidarrCliHandler, LidarrCommand};
use radarr::{RadarrCliHandler, RadarrCommand};
use sonarr::{SonarrCliHandler, SonarrCommand};
@@ -43,6 +44,12 @@ pub enum Command {
#[arg(long, help = "Disable colored log output")]
no_color: bool,
},
#[command(about = indoc!{"
Print the full path to the default configuration file.
This file can be changed to another location using the '--config-file' flag
"})]
ConfigPath,
}
pub trait CliCommandHandler<'a, 'b, T: Into<Command>> {
+1 -1
View File
@@ -1,7 +1,7 @@
use std::sync::Arc;
use anyhow::Result;
use clap::{ArgAction, Subcommand, arg, command};
use clap::{ArgAction, Subcommand};
use tokio::sync::Mutex;
use super::RadarrCommand;
+1 -1
View File
@@ -1,7 +1,7 @@
use std::sync::Arc;
use anyhow::Result;
use clap::{Subcommand, command};
use clap::Subcommand;
use tokio::sync::Mutex;
use crate::{
+1 -1
View File
@@ -1,7 +1,7 @@
use std::sync::Arc;
use anyhow::Result;
use clap::{Subcommand, command};
use clap::Subcommand;
use tokio::sync::Mutex;
use crate::{
+1 -1
View File
@@ -249,7 +249,7 @@ impl<'a, 'b> CliCommandHandler<'a, 'b, SonarrListCommand> for SonarrListCommandH
} => {
let resp = self
.network
.handle_network_event(SonarrEvent::GetSeasonHistory((series_id, season_number)).into())
.handle_network_event(SonarrEvent::GetSeasonHistory(series_id, season_number).into())
.await?;
serde_json::to_string_pretty(&resp)?
}
+1 -1
View File
@@ -543,7 +543,7 @@ mod tests {
mock_network
.expect_handle_network_event()
.with(eq::<NetworkEvent>(
SonarrEvent::GetSeasonHistory((expected_series_id, expected_season_number)).into(),
SonarrEvent::GetSeasonHistory(expected_series_id, expected_season_number).into(),
))
.times(1)
.returning(|_| {
@@ -30,7 +30,7 @@ pub enum SonarrManualSearchCommand {
episode_id: i64,
},
#[command(
about = "Trigger a manual search of releases for the given season corresponding to the series with the given ID"
about = "Trigger a manual search of full-season releases (full_season: true) for the given season corresponding to the series with the given ID"
)]
Season {
#[arg(
@@ -88,7 +88,7 @@ impl<'a, 'b> CliCommandHandler<'a, 'b, SonarrManualSearchCommand>
serde_json::to_string_pretty(&seasons_vec)?
}
Err(e) => return Err(e),
_ => serde_json::to_string_pretty(&json!({"message": "Failed to parse response"}))?,
_ => serde_json::to_string_pretty(&json!({"message": "Unexpected response format"}))?,
}
}
SonarrManualSearchCommand::Season {
@@ -98,7 +98,7 @@ impl<'a, 'b> CliCommandHandler<'a, 'b, SonarrManualSearchCommand>
println!("Searching for season releases. This may take a minute...");
match self
.network
.handle_network_event(SonarrEvent::GetSeasonReleases((series_id, season_number)).into())
.handle_network_event(SonarrEvent::GetSeasonReleases(series_id, season_number).into())
.await
{
Ok(Serdeable::Sonarr(SonarrSerdeable::Releases(releases_vec))) => {
@@ -176,7 +176,7 @@ mod tests {
mock_network
.expect_handle_network_event()
.with(eq::<NetworkEvent>(
SonarrEvent::GetSeasonReleases((expected_series_id, expected_season_number)).into(),
SonarrEvent::GetSeasonReleases(expected_series_id, expected_season_number).into(),
))
.times(1)
.returning(|_| {
+1 -1
View File
@@ -297,7 +297,7 @@ impl<'a, 'b> CliCommandHandler<'a, 'b, SonarrCommand> for SonarrCliHandler<'a, '
let resp = self
.network
.handle_network_event(
SonarrEvent::ToggleSeasonMonitoring((series_id, season_number)).into(),
SonarrEvent::ToggleSeasonMonitoring(series_id, season_number).into(),
)
.await?;
serde_json::to_string_pretty(&resp)?
+1 -1
View File
@@ -755,7 +755,7 @@ mod tests {
mock_network
.expect_handle_network_event()
.with(eq::<NetworkEvent>(
SonarrEvent::ToggleSeasonMonitoring((expected_series_id, expected_season_number)).into(),
SonarrEvent::ToggleSeasonMonitoring(expected_series_id, expected_season_number).into(),
))
.times(1)
.returning(|_| {
@@ -94,7 +94,7 @@ impl<'a, 'b> CliCommandHandler<'a, 'b, SonarrTriggerAutomaticSearchCommand>
let resp = self
.network
.handle_network_event(
SonarrEvent::TriggerAutomaticSeasonSearch((series_id, season_number)).into(),
SonarrEvent::TriggerAutomaticSeasonSearch(series_id, season_number).into(),
)
.await?;
serde_json::to_string_pretty(&resp)?
@@ -197,7 +197,7 @@ mod tests {
mock_network
.expect_handle_network_event()
.with(eq::<NetworkEvent>(
SonarrEvent::TriggerAutomaticSeasonSearch((expected_series_id, expected_season_number))
SonarrEvent::TriggerAutomaticSeasonSearch(expected_series_id, expected_season_number)
.into(),
))
.times(1)
+58 -5
View File
@@ -20,10 +20,10 @@ mod tests {
use crate::handlers::{handle_events, populate_keymapping_table};
use crate::models::HorizontallyScrollableText;
use crate::models::Route;
use crate::models::servarr_data::ActiveKeybindingBlock;
use crate::models::servarr_data::lidarr::lidarr_data::ActiveLidarrBlock;
use crate::models::servarr_data::radarr::radarr_data::{ActiveRadarrBlock, RadarrData};
use crate::models::servarr_data::sonarr::sonarr_data::ActiveSonarrBlock;
use crate::models::servarr_data::{ActiveKeybindingBlock, Notification};
use crate::models::servarr_models::KeybindingItem;
use crate::models::stateful_table::StatefulTable;
@@ -174,6 +174,26 @@ mod tests {
);
}
#[test]
fn test_handle_clear_notification() {
let mut app = App::test_default();
app.notification = Some(Notification::new(
"Test".to_owned(),
"Test".to_owned(),
true,
));
app.push_navigation_stack(ActiveRadarrBlock::Movies.into());
app.push_navigation_stack(ActiveRadarrBlock::MovieDetails.into());
handle_events(DEFAULT_KEYBINDINGS.esc.key, &mut app);
assert_none!(app.notification);
assert_eq!(
app.get_current_route(),
ActiveRadarrBlock::MovieDetails.into()
);
}
#[rstest]
fn test_handle_prompt_toggle_left_right_radarr(#[values(Key::Left, Key::Right)] key: Key) {
let mut app = App::test_default();
@@ -211,8 +231,8 @@ mod tests {
let expected_keybinding_items = Vec::from(SERVARR_CONTEXT_CLUES)
.iter()
.map(|(key, desc)| {
let (key, alt_key) = if key.alt.is_some() {
(key.key.to_string(), key.alt.as_ref().unwrap().to_string())
let (key, alt_key) = if let Some(key1) = key.alt {
(key.key.to_string(), key1.to_string())
} else {
(key.key.to_string(), String::new())
};
@@ -284,9 +304,42 @@ mod tests {
);
}
#[test]
fn test_handle_events_esc_clears_notification() {
let mut app = App::test_default();
app.notification = Some(Notification::new(
"Download Result".to_owned(),
"Download request sent successfully".to_owned(),
true,
));
app.push_navigation_stack(ActiveRadarrBlock::Movies.into());
handle_events(DEFAULT_KEYBINDINGS.esc.key, &mut app);
assert_none!(app.notification);
assert_eq!(app.get_current_route(), ActiveRadarrBlock::Movies.into());
}
#[test]
fn test_handle_events_esc_does_not_clear_notification_when_none() {
let mut app = App::test_default();
app
.data
.radarr_data
.movies
.set_items(vec![Movie::default()]);
app.push_navigation_stack(ActiveRadarrBlock::Movies.into());
app.push_navigation_stack(ActiveRadarrBlock::SearchMovie.into());
handle_events(DEFAULT_KEYBINDINGS.esc.key, &mut app);
assert_none!(app.notification);
assert_navigation_popped!(app, ActiveRadarrBlock::Movies.into());
}
fn context_clue_to_keybinding_item(key: &KeyBinding, desc: &&str) -> KeybindingItem {
let (key, alt_key) = if key.alt.is_some() {
(key.key.to_string(), key.alt.as_ref().unwrap().to_string())
let (key, alt_key) = if let Some(key1) = key.alt {
(key.key.to_string(), key1.to_string())
} else {
(key.key.to_string(), String::new())
};
@@ -0,0 +1,615 @@
#[cfg(test)]
mod tests {
use std::cmp::Ordering;
use chrono::DateTime;
use pretty_assertions::{assert_eq, assert_str_eq};
use rstest::rstest;
use strum::IntoEnumIterator;
use crate::app::App;
use crate::app::key_binding::DEFAULT_KEYBINDINGS;
use crate::assert_navigation_pushed;
use crate::event::Key;
use crate::handlers::KeyEventHandler;
use crate::handlers::lidarr_handlers::blocklist::{BlocklistHandler, blocklist_sorting_options};
use crate::models::lidarr_models::{Artist, BlocklistItem};
use crate::models::servarr_data::lidarr::lidarr_data::{ActiveLidarrBlock, BLOCKLIST_BLOCKS};
use crate::models::servarr_models::{Quality, QualityWrapper};
use crate::network::lidarr_network::lidarr_network_test_utils::test_utils::artist;
mod test_handle_delete {
use pretty_assertions::assert_eq;
use super::*;
const DELETE_KEY: Key = DEFAULT_KEYBINDINGS.delete.key;
#[test]
fn test_delete_blocklist_item_prompt() {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
BlocklistHandler::new(DELETE_KEY, &mut app, ActiveLidarrBlock::Blocklist, None).handle();
assert_navigation_pushed!(app, ActiveLidarrBlock::DeleteBlocklistItemPrompt.into());
}
#[test]
fn test_delete_blocklist_item_no_op_when_not_ready() {
let mut app = App::test_default();
app.is_loading = true;
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
BlocklistHandler::new(DELETE_KEY, &mut app, ActiveLidarrBlock::Blocklist, None).handle();
assert_eq!(app.get_current_route(), ActiveLidarrBlock::Blocklist.into());
}
}
mod test_handle_left_right_action {
use pretty_assertions::assert_eq;
use rstest::rstest;
use super::*;
use crate::assert_navigation_pushed;
#[rstest]
fn test_blocklist_tab_left(#[values(true, false)] is_ready: bool) {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.is_loading = is_ready;
app.data.lidarr_data.main_tabs.set_index(2);
BlocklistHandler::new(
DEFAULT_KEYBINDINGS.left.key,
&mut app,
ActiveLidarrBlock::Blocklist,
None,
)
.handle();
assert_eq!(
app.data.lidarr_data.main_tabs.get_active_route(),
ActiveLidarrBlock::Downloads.into()
);
assert_navigation_pushed!(app, ActiveLidarrBlock::Downloads.into());
}
#[rstest]
fn test_blocklist_tab_right(#[values(true, false)] is_ready: bool) {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.is_loading = is_ready;
app.data.lidarr_data.main_tabs.set_index(2);
BlocklistHandler::new(
DEFAULT_KEYBINDINGS.right.key,
&mut app,
ActiveLidarrBlock::Blocklist,
None,
)
.handle();
assert_eq!(
app.data.lidarr_data.main_tabs.get_active_route(),
ActiveLidarrBlock::History.into()
);
assert_navigation_pushed!(app, ActiveLidarrBlock::History.into());
}
#[rstest]
fn test_blocklist_left_right_prompt_toggle(
#[values(
ActiveLidarrBlock::DeleteBlocklistItemPrompt,
ActiveLidarrBlock::BlocklistClearAllItemsPrompt
)]
active_lidarr_block: ActiveLidarrBlock,
#[values(DEFAULT_KEYBINDINGS.left.key, DEFAULT_KEYBINDINGS.right.key)] key: Key,
) {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
BlocklistHandler::new(key, &mut app, active_lidarr_block, None).handle();
assert!(app.data.lidarr_data.prompt_confirm);
BlocklistHandler::new(key, &mut app, active_lidarr_block, None).handle();
assert!(!app.data.lidarr_data.prompt_confirm);
}
}
mod test_handle_submit {
use crate::assert_navigation_popped;
use crate::network::lidarr_network::LidarrEvent;
use pretty_assertions::assert_eq;
use rstest::rstest;
use super::*;
const SUBMIT_KEY: Key = DEFAULT_KEYBINDINGS.submit.key;
#[test]
fn test_blocklist_submit() {
let mut app = App::test_default();
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
BlocklistHandler::new(SUBMIT_KEY, &mut app, ActiveLidarrBlock::Blocklist, None).handle();
assert_navigation_pushed!(app, ActiveLidarrBlock::BlocklistItemDetails.into());
}
#[test]
fn test_blocklist_submit_no_op_when_not_ready() {
let mut app = App::test_default();
app.is_loading = true;
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
BlocklistHandler::new(SUBMIT_KEY, &mut app, ActiveLidarrBlock::Blocklist, None).handle();
assert_eq!(app.get_current_route(), ActiveLidarrBlock::Blocklist.into());
}
#[rstest]
#[case(
ActiveLidarrBlock::Blocklist,
ActiveLidarrBlock::DeleteBlocklistItemPrompt,
LidarrEvent::DeleteBlocklistItem(3)
)]
#[case(
ActiveLidarrBlock::Blocklist,
ActiveLidarrBlock::BlocklistClearAllItemsPrompt,
LidarrEvent::ClearBlocklist
)]
fn test_blocklist_prompt_confirm_submit(
#[case] base_route: ActiveLidarrBlock,
#[case] prompt_block: ActiveLidarrBlock,
#[case] expected_action: LidarrEvent,
) {
let mut app = App::test_default();
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
app.data.lidarr_data.prompt_confirm = true;
app.push_navigation_stack(base_route.into());
app.push_navigation_stack(prompt_block.into());
BlocklistHandler::new(SUBMIT_KEY, &mut app, prompt_block, None).handle();
assert!(app.data.lidarr_data.prompt_confirm);
assert_some_eq_x!(
&app.data.lidarr_data.prompt_confirm_action,
&expected_action
);
assert_navigation_popped!(app, base_route.into());
}
#[rstest]
fn test_blocklist_prompt_decline_submit(
#[values(
ActiveLidarrBlock::DeleteBlocklistItemPrompt,
ActiveLidarrBlock::BlocklistClearAllItemsPrompt
)]
prompt_block: ActiveLidarrBlock,
) {
let mut app = App::test_default();
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.push_navigation_stack(prompt_block.into());
BlocklistHandler::new(SUBMIT_KEY, &mut app, prompt_block, None).handle();
assert!(!app.data.lidarr_data.prompt_confirm);
assert_none!(app.data.lidarr_data.prompt_confirm_action);
assert_navigation_popped!(app, ActiveLidarrBlock::Blocklist.into());
}
}
mod test_handle_esc {
use rstest::rstest;
use super::*;
use crate::assert_navigation_popped;
const ESC_KEY: Key = DEFAULT_KEYBINDINGS.esc.key;
#[rstest]
#[case(
ActiveLidarrBlock::Blocklist,
ActiveLidarrBlock::DeleteBlocklistItemPrompt
)]
#[case(
ActiveLidarrBlock::Blocklist,
ActiveLidarrBlock::BlocklistClearAllItemsPrompt
)]
fn test_blocklist_prompt_blocks_esc(
#[case] base_block: ActiveLidarrBlock,
#[case] prompt_block: ActiveLidarrBlock,
) {
let mut app = App::test_default();
app.push_navigation_stack(base_block.into());
app.push_navigation_stack(prompt_block.into());
app.data.lidarr_data.prompt_confirm = true;
BlocklistHandler::new(ESC_KEY, &mut app, prompt_block, None).handle();
assert_navigation_popped!(app, base_block.into());
assert!(!app.data.lidarr_data.prompt_confirm);
}
#[test]
fn test_esc_blocklist_item_details() {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.push_navigation_stack(ActiveLidarrBlock::BlocklistItemDetails.into());
BlocklistHandler::new(
ESC_KEY,
&mut app,
ActiveLidarrBlock::BlocklistItemDetails,
None,
)
.handle();
assert_navigation_popped!(app, ActiveLidarrBlock::Blocklist.into());
}
#[rstest]
fn test_default_esc(#[values(true, false)] is_ready: bool) {
let mut app = App::test_default();
app.is_loading = is_ready;
app.error = "test error".to_owned().into();
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
BlocklistHandler::new(ESC_KEY, &mut app, ActiveLidarrBlock::Blocklist, None).handle();
assert_navigation_popped!(app, ActiveLidarrBlock::Blocklist.into());
assert_is_empty!(app.error.text);
}
}
mod test_handle_key_char {
use pretty_assertions::assert_eq;
use rstest::rstest;
use crate::network::lidarr_network::LidarrEvent;
use super::*;
use crate::{assert_navigation_popped, assert_navigation_pushed};
#[test]
fn test_refresh_blocklist_key() {
let mut app = App::test_default();
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
BlocklistHandler::new(
DEFAULT_KEYBINDINGS.refresh.key,
&mut app,
ActiveLidarrBlock::Blocklist,
None,
)
.handle();
assert_navigation_pushed!(app, ActiveLidarrBlock::Blocklist.into());
assert!(app.should_refresh);
}
#[test]
fn test_refresh_blocklist_key_no_op_when_not_ready() {
let mut app = App::test_default();
app.is_loading = true;
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
BlocklistHandler::new(
DEFAULT_KEYBINDINGS.refresh.key,
&mut app,
ActiveLidarrBlock::Blocklist,
None,
)
.handle();
assert_eq!(app.get_current_route(), ActiveLidarrBlock::Blocklist.into());
assert!(!app.should_refresh);
}
#[test]
fn test_clear_blocklist_key() {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
BlocklistHandler::new(
DEFAULT_KEYBINDINGS.clear.key,
&mut app,
ActiveLidarrBlock::Blocklist,
None,
)
.handle();
assert_navigation_pushed!(app, ActiveLidarrBlock::BlocklistClearAllItemsPrompt.into());
}
#[test]
fn test_clear_blocklist_key_no_op_when_not_ready() {
let mut app = App::test_default();
app.is_loading = true;
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
BlocklistHandler::new(
DEFAULT_KEYBINDINGS.clear.key,
&mut app,
ActiveLidarrBlock::Blocklist,
None,
)
.handle();
assert_eq!(app.get_current_route(), ActiveLidarrBlock::Blocklist.into());
}
#[rstest]
#[case(
ActiveLidarrBlock::Blocklist,
ActiveLidarrBlock::DeleteBlocklistItemPrompt,
LidarrEvent::DeleteBlocklistItem(3)
)]
#[case(
ActiveLidarrBlock::Blocklist,
ActiveLidarrBlock::BlocklistClearAllItemsPrompt,
LidarrEvent::ClearBlocklist
)]
fn test_blocklist_prompt_confirm(
#[case] base_route: ActiveLidarrBlock,
#[case] prompt_block: ActiveLidarrBlock,
#[case] expected_action: LidarrEvent,
) {
let mut app = App::test_default();
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
app.push_navigation_stack(base_route.into());
app.push_navigation_stack(prompt_block.into());
BlocklistHandler::new(
DEFAULT_KEYBINDINGS.confirm.key,
&mut app,
prompt_block,
None,
)
.handle();
assert!(app.data.lidarr_data.prompt_confirm);
assert_some_eq_x!(
&app.data.lidarr_data.prompt_confirm_action,
&expected_action
);
assert_navigation_popped!(app, base_route.into());
}
}
#[test]
fn test_blocklist_sorting_options_artist_name() {
let expected_cmp_fn: fn(&BlocklistItem, &BlocklistItem) -> Ordering = |a, b| {
a.artist
.artist_name
.text
.to_lowercase()
.cmp(&b.artist.artist_name.text.to_lowercase())
};
let mut expected_blocklist_vec = blocklist_vec();
expected_blocklist_vec.sort_by(expected_cmp_fn);
let sort_option = blocklist_sorting_options()[0].clone();
let mut sorted_blocklist_vec = blocklist_vec();
sorted_blocklist_vec.sort_by(sort_option.cmp_fn.unwrap());
assert_eq!(sorted_blocklist_vec, expected_blocklist_vec);
assert_str_eq!(sort_option.name, "Artist Name");
}
#[test]
fn test_blocklist_sorting_options_source_title() {
let expected_cmp_fn: fn(&BlocklistItem, &BlocklistItem) -> Ordering = |a, b| {
a.source_title
.to_lowercase()
.cmp(&b.source_title.to_lowercase())
};
let mut expected_blocklist_vec = blocklist_vec();
expected_blocklist_vec.sort_by(expected_cmp_fn);
let sort_option = blocklist_sorting_options()[1].clone();
let mut sorted_blocklist_vec = blocklist_vec();
sorted_blocklist_vec.sort_by(sort_option.cmp_fn.unwrap());
assert_eq!(sorted_blocklist_vec, expected_blocklist_vec);
assert_str_eq!(sort_option.name, "Source Title");
}
#[test]
fn test_blocklist_sorting_options_quality() {
let expected_cmp_fn: fn(&BlocklistItem, &BlocklistItem) -> Ordering = |a, b| {
a.quality
.quality
.name
.to_lowercase()
.cmp(&b.quality.quality.name.to_lowercase())
};
let mut expected_blocklist_vec = blocklist_vec();
expected_blocklist_vec.sort_by(expected_cmp_fn);
let sort_option = blocklist_sorting_options()[2].clone();
let mut sorted_blocklist_vec = blocklist_vec();
sorted_blocklist_vec.sort_by(sort_option.cmp_fn.unwrap());
assert_eq!(sorted_blocklist_vec, expected_blocklist_vec);
assert_str_eq!(sort_option.name, "Quality");
}
#[test]
fn test_blocklist_sorting_options_date() {
let expected_cmp_fn: fn(&BlocklistItem, &BlocklistItem) -> Ordering =
|a, b| a.date.cmp(&b.date);
let mut expected_blocklist_vec = blocklist_vec();
expected_blocklist_vec.sort_by(expected_cmp_fn);
let sort_option = blocklist_sorting_options()[3].clone();
let mut sorted_blocklist_vec = blocklist_vec();
sorted_blocklist_vec.sort_by(sort_option.cmp_fn.unwrap());
assert_eq!(sorted_blocklist_vec, expected_blocklist_vec);
assert_str_eq!(sort_option.name, "Date");
}
#[test]
fn test_blocklist_handler_accepts() {
ActiveLidarrBlock::iter().for_each(|active_lidarr_block| {
if BLOCKLIST_BLOCKS.contains(&active_lidarr_block) {
assert!(BlocklistHandler::accepts(active_lidarr_block));
} else {
assert!(!BlocklistHandler::accepts(active_lidarr_block));
}
})
}
#[rstest]
fn test_blocklist_handler_ignore_special_keys(
#[values(true, false)] ignore_special_keys_for_textbox_input: bool,
) {
let mut app = App::test_default();
app.ignore_special_keys_for_textbox_input = ignore_special_keys_for_textbox_input;
let handler = BlocklistHandler::new(
DEFAULT_KEYBINDINGS.esc.key,
&mut app,
ActiveLidarrBlock::default(),
None,
);
assert_eq!(
handler.ignore_special_keys(),
ignore_special_keys_for_textbox_input
);
}
#[test]
fn test_extract_blocklist_item_id() {
let mut app = App::test_default();
app.data.lidarr_data.blocklist.set_items(blocklist_vec());
let blocklist_item_id = BlocklistHandler::new(
DEFAULT_KEYBINDINGS.esc.key,
&mut app,
ActiveLidarrBlock::Blocklist,
None,
)
.extract_blocklist_item_id();
assert_eq!(blocklist_item_id, 3);
}
#[test]
fn test_blocklist_handler_not_ready_when_loading() {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.is_loading = true;
let handler = BlocklistHandler::new(
DEFAULT_KEYBINDINGS.esc.key,
&mut app,
ActiveLidarrBlock::Blocklist,
None,
);
assert!(!handler.is_ready());
}
#[test]
fn test_blocklist_handler_not_ready_when_blocklist_is_empty() {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.is_loading = false;
let handler = BlocklistHandler::new(
DEFAULT_KEYBINDINGS.esc.key,
&mut app,
ActiveLidarrBlock::Blocklist,
None,
);
assert!(!handler.is_ready());
}
#[test]
fn test_blocklist_handler_ready_when_not_loading_and_blocklist_is_not_empty() {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::Blocklist.into());
app.is_loading = false;
app
.data
.lidarr_data
.blocklist
.set_items(vec![BlocklistItem::default()]);
let handler = BlocklistHandler::new(
DEFAULT_KEYBINDINGS.esc.key,
&mut app,
ActiveLidarrBlock::Blocklist,
None,
);
assert!(handler.is_ready());
}
fn blocklist_vec() -> Vec<BlocklistItem> {
vec![
BlocklistItem {
id: 3,
source_title: "test 1".to_owned(),
quality: QualityWrapper {
quality: Quality {
name: "Lossless".to_owned(),
},
},
date: DateTime::from(DateTime::parse_from_rfc3339("2024-01-10T07:28:45Z").unwrap()),
artist: Artist {
artist_name: "test 3".into(),
..artist()
},
..BlocklistItem::default()
},
BlocklistItem {
id: 2,
source_title: "test 2".to_owned(),
quality: QualityWrapper {
quality: Quality {
name: "Lossy".to_owned(),
},
},
date: DateTime::from(DateTime::parse_from_rfc3339("2024-02-10T07:28:45Z").unwrap()),
artist: Artist {
artist_name: "test 2".into(),
..artist()
},
..BlocklistItem::default()
},
BlocklistItem {
id: 1,
source_title: "test 3".to_owned(),
quality: QualityWrapper {
quality: Quality {
name: "Lossless".to_owned(),
},
},
date: DateTime::from(DateTime::parse_from_rfc3339("2024-03-10T07:28:45Z").unwrap()),
artist: Artist {
artist_name: "".into(),
..artist()
},
..BlocklistItem::default()
},
]
}
}
@@ -0,0 +1,222 @@
use crate::app::App;
use crate::event::Key;
use crate::handlers::lidarr_handlers::handle_change_tab_left_right_keys;
use crate::handlers::table_handler::{TableHandlingConfig, handle_table};
use crate::handlers::{KeyEventHandler, handle_clear_errors, handle_prompt_toggle};
use crate::matches_key;
use crate::models::Route;
use crate::models::lidarr_models::BlocklistItem;
use crate::models::servarr_data::lidarr::lidarr_data::{ActiveLidarrBlock, BLOCKLIST_BLOCKS};
use crate::models::stateful_table::SortOption;
use crate::network::lidarr_network::LidarrEvent;
#[cfg(test)]
#[path = "blocklist_handler_tests.rs"]
mod blocklist_handler_tests;
pub(super) struct BlocklistHandler<'a, 'b> {
key: Key,
app: &'a mut App<'b>,
active_lidarr_block: ActiveLidarrBlock,
_context: Option<ActiveLidarrBlock>,
}
impl BlocklistHandler<'_, '_> {
fn extract_blocklist_item_id(&self) -> i64 {
self.app.data.lidarr_data.blocklist.current_selection().id
}
}
impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveLidarrBlock> for BlocklistHandler<'a, 'b> {
fn handle(&mut self) {
let blocklist_table_handling_config =
TableHandlingConfig::new(ActiveLidarrBlock::Blocklist.into())
.sorting_block(ActiveLidarrBlock::BlocklistSortPrompt.into())
.sort_options(blocklist_sorting_options());
if !handle_table(
self,
|app| &mut app.data.lidarr_data.blocklist,
blocklist_table_handling_config,
) {
self.handle_key_event();
}
}
fn accepts(active_block: ActiveLidarrBlock) -> bool {
BLOCKLIST_BLOCKS.contains(&active_block)
}
fn new(
key: Key,
app: &'a mut App<'b>,
active_block: ActiveLidarrBlock,
context: Option<ActiveLidarrBlock>,
) -> Self {
BlocklistHandler {
key,
app,
active_lidarr_block: active_block,
_context: context,
}
}
fn get_key(&self) -> Key {
self.key
}
fn ignore_special_keys(&self) -> bool {
self.app.ignore_special_keys_for_textbox_input
}
fn is_ready(&self) -> bool {
!self.app.is_loading && !self.app.data.lidarr_data.blocklist.is_empty()
}
fn handle_scroll_up(&mut self) {}
fn handle_scroll_down(&mut self) {}
fn handle_home(&mut self) {}
fn handle_end(&mut self) {}
fn handle_delete(&mut self) {
if self.active_lidarr_block == ActiveLidarrBlock::Blocklist {
self
.app
.push_navigation_stack(ActiveLidarrBlock::DeleteBlocklistItemPrompt.into());
}
}
fn handle_left_right_action(&mut self) {
match self.active_lidarr_block {
ActiveLidarrBlock::Blocklist => handle_change_tab_left_right_keys(self.app, self.key),
ActiveLidarrBlock::DeleteBlocklistItemPrompt
| ActiveLidarrBlock::BlocklistClearAllItemsPrompt => handle_prompt_toggle(self.app, self.key),
_ => {}
}
}
fn handle_submit(&mut self) {
match self.active_lidarr_block {
ActiveLidarrBlock::DeleteBlocklistItemPrompt => {
if self.app.data.lidarr_data.prompt_confirm {
self.app.data.lidarr_data.prompt_confirm_action = Some(LidarrEvent::DeleteBlocklistItem(
self.extract_blocklist_item_id(),
));
}
self.app.pop_navigation_stack();
}
ActiveLidarrBlock::BlocklistClearAllItemsPrompt => {
if self.app.data.lidarr_data.prompt_confirm {
self.app.data.lidarr_data.prompt_confirm_action = Some(LidarrEvent::ClearBlocklist);
}
self.app.pop_navigation_stack();
}
ActiveLidarrBlock::Blocklist => {
self
.app
.push_navigation_stack(ActiveLidarrBlock::BlocklistItemDetails.into());
}
_ => (),
}
}
fn handle_esc(&mut self) {
match self.active_lidarr_block {
ActiveLidarrBlock::DeleteBlocklistItemPrompt
| ActiveLidarrBlock::BlocklistClearAllItemsPrompt => {
self.app.pop_navigation_stack();
self.app.data.lidarr_data.prompt_confirm = false;
}
ActiveLidarrBlock::BlocklistItemDetails | ActiveLidarrBlock::BlocklistSortPrompt => {
self.app.pop_navigation_stack();
}
_ => handle_clear_errors(self.app),
}
}
fn handle_char_key_event(&mut self) {
let key = self.key;
match self.active_lidarr_block {
ActiveLidarrBlock::Blocklist => match self.key {
_ if matches_key!(refresh, key) => {
self.app.should_refresh = true;
}
_ if matches_key!(clear, key) => {
self
.app
.push_navigation_stack(ActiveLidarrBlock::BlocklistClearAllItemsPrompt.into());
}
_ => (),
},
ActiveLidarrBlock::DeleteBlocklistItemPrompt => {
if matches_key!(confirm, key) {
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action = Some(LidarrEvent::DeleteBlocklistItem(
self.extract_blocklist_item_id(),
));
self.app.pop_navigation_stack();
}
}
ActiveLidarrBlock::BlocklistClearAllItemsPrompt => {
if matches_key!(confirm, key) {
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action = Some(LidarrEvent::ClearBlocklist);
self.app.pop_navigation_stack();
}
}
_ => (),
}
}
fn app_mut(&mut self) -> &mut App<'b> {
self.app
}
fn current_route(&self) -> Route {
self.app.get_current_route()
}
}
fn blocklist_sorting_options() -> Vec<SortOption<BlocklistItem>> {
vec![
SortOption {
name: "Artist Name",
cmp_fn: Some(|a, b| {
a.artist
.artist_name
.text
.to_lowercase()
.cmp(&b.artist.artist_name.text.to_lowercase())
}),
},
SortOption {
name: "Source Title",
cmp_fn: Some(|a, b| {
a.source_title
.to_lowercase()
.cmp(&b.source_title.to_lowercase())
}),
},
SortOption {
name: "Quality",
cmp_fn: Some(|a, b| {
a.quality
.quality
.name
.to_lowercase()
.cmp(&b.quality.quality.name.to_lowercase())
}),
},
SortOption {
name: "Date",
cmp_fn: Some(|a, b| a.date.cmp(&b.date)),
},
]
}
@@ -99,9 +99,9 @@ mod tests {
assert_eq!(
app.data.lidarr_data.main_tabs.get_active_route(),
ActiveLidarrBlock::History.into()
ActiveLidarrBlock::Blocklist.into()
);
assert_navigation_pushed!(app, ActiveLidarrBlock::History.into());
assert_navigation_pushed!(app, ActiveLidarrBlock::Blocklist.into());
}
#[rstest]
@@ -29,7 +29,7 @@ mod tests {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::History.into());
app.is_loading = is_ready;
app.data.lidarr_data.main_tabs.set_index(2);
app.data.lidarr_data.main_tabs.set_index(3);
HistoryHandler::new(
DEFAULT_KEYBINDINGS.left.key,
@@ -41,9 +41,9 @@ mod tests {
assert_eq!(
app.data.lidarr_data.main_tabs.get_active_route(),
ActiveLidarrBlock::Downloads.into()
ActiveLidarrBlock::Blocklist.into()
);
assert_navigation_pushed!(app, ActiveLidarrBlock::Downloads.into());
assert_navigation_pushed!(app, ActiveLidarrBlock::Blocklist.into());
}
#[rstest]
@@ -51,7 +51,7 @@ mod tests {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::History.into());
app.is_loading = is_ready;
app.data.lidarr_data.main_tabs.set_index(2);
app.data.lidarr_data.main_tabs.set_index(3);
HistoryHandler::new(
DEFAULT_KEYBINDINGS.right.key,
@@ -506,18 +506,17 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveLidarrBlock> for EditIndexerHandler<'
.tags
);
}
ActiveLidarrBlock::EditIndexerPrompt => {
ActiveLidarrBlock::EditIndexerPrompt
if self.app.data.lidarr_data.selected_block.get_active_block()
== ActiveLidarrBlock::EditIndexerConfirmPrompt
&& matches_key!(confirm, self.key)
{
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action =
Some(LidarrEvent::EditIndexer(self.build_edit_indexer_params()));
self.app.should_refresh = true;
&& matches_key!(confirm, self.key) =>
{
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action =
Some(LidarrEvent::EditIndexer(self.build_edit_indexer_params()));
self.app.should_refresh = true;
self.app.pop_navigation_stack();
}
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -106,10 +106,10 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveLidarrBlock> for IndexerSettingsHandl
indexer_settings.maximum_size -= 1;
}
}
ActiveLidarrBlock::IndexerSettingsRssSyncIntervalInput => {
if indexer_settings.rss_sync_interval > 0 {
indexer_settings.rss_sync_interval -= 1;
}
ActiveLidarrBlock::IndexerSettingsRssSyncIntervalInput
if indexer_settings.rss_sync_interval > 0 =>
{
indexer_settings.rss_sync_interval -= 1;
}
_ => (),
}
@@ -67,7 +67,7 @@ mod tests {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::Indexers.into());
app.is_loading = is_ready;
app.data.lidarr_data.main_tabs.set_index(4);
app.data.lidarr_data.main_tabs.set_index(5);
IndexersHandler::new(
DEFAULT_KEYBINDINGS.left.key,
@@ -89,7 +89,7 @@ mod tests {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::Indexers.into());
app.is_loading = is_ready;
app.data.lidarr_data.main_tabs.set_index(4);
app.data.lidarr_data.main_tabs.set_index(5);
IndexersHandler::new(
DEFAULT_KEYBINDINGS.right.key,
@@ -591,16 +591,15 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveLidarrBlock> for AddArtistHandler<'a,
.tags
)
}
ActiveLidarrBlock::AddArtistPrompt => {
ActiveLidarrBlock::AddArtistPrompt
if self.app.data.lidarr_data.selected_block.get_active_block()
== ActiveLidarrBlock::AddArtistConfirmPrompt
&& matches_key!(confirm, key)
{
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action =
Some(LidarrEvent::AddArtist(self.build_add_artist_body()));
self.app.pop_navigation_stack();
}
&& matches_key!(confirm, key) =>
{
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action =
Some(LidarrEvent::AddArtist(self.build_add_artist_body()));
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -293,16 +293,16 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveLidarrBlock> for ArtistDetailsHandler
self.app.data.lidarr_data.selected_block =
BlockSelectionState::new(EDIT_ARTIST_SELECTION_BLOCKS);
}
_ if matches_key!(toggle_monitoring, key) => {
if !self.app.data.lidarr_data.albums.is_empty() {
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action =
Some(LidarrEvent::ToggleAlbumMonitoring(self.extract_album_id()));
_ if matches_key!(toggle_monitoring, key)
&& !self.app.data.lidarr_data.albums.is_empty() =>
{
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action =
Some(LidarrEvent::ToggleAlbumMonitoring(self.extract_album_id()));
self
.app
.pop_and_push_navigation_stack(self.active_lidarr_block.into());
}
self
.app
.pop_and_push_navigation_stack(self.active_lidarr_block.into());
}
_ => (),
},
@@ -428,18 +428,17 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveLidarrBlock> for EditArtistHandler<'a
.tags
)
}
ActiveLidarrBlock::EditArtistPrompt => {
ActiveLidarrBlock::EditArtistPrompt
if self.app.data.lidarr_data.selected_block.get_active_block()
== ActiveLidarrBlock::EditArtistConfirmPrompt
&& matches_key!(confirm, key)
{
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action =
Some(LidarrEvent::EditArtist(self.build_edit_artist_params()));
self.app.should_refresh = true;
&& matches_key!(confirm, key) =>
{
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action =
Some(LidarrEvent::EditArtist(self.build_edit_artist_params()));
self.app.should_refresh = true;
self.app.pop_navigation_stack();
}
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -53,11 +53,12 @@ mod tests {
#[rstest]
#[case(0, ActiveLidarrBlock::System, ActiveLidarrBlock::Downloads)]
#[case(1, ActiveLidarrBlock::Artists, ActiveLidarrBlock::History)]
#[case(2, ActiveLidarrBlock::Downloads, ActiveLidarrBlock::RootFolders)]
#[case(3, ActiveLidarrBlock::History, ActiveLidarrBlock::Indexers)]
#[case(4, ActiveLidarrBlock::RootFolders, ActiveLidarrBlock::System)]
#[case(5, ActiveLidarrBlock::Indexers, ActiveLidarrBlock::Artists)]
#[case(1, ActiveLidarrBlock::Artists, ActiveLidarrBlock::Blocklist)]
#[case(2, ActiveLidarrBlock::Downloads, ActiveLidarrBlock::History)]
#[case(3, ActiveLidarrBlock::Blocklist, ActiveLidarrBlock::RootFolders)]
#[case(4, ActiveLidarrBlock::History, ActiveLidarrBlock::Indexers)]
#[case(5, ActiveLidarrBlock::RootFolders, ActiveLidarrBlock::System)]
#[case(6, ActiveLidarrBlock::Indexers, ActiveLidarrBlock::Artists)]
fn test_lidarr_handler_change_tab_left_right_keys(
#[case] index: usize,
#[case] left_block: ActiveLidarrBlock,
@@ -87,11 +88,12 @@ mod tests {
#[rstest]
#[case(0, ActiveLidarrBlock::System, ActiveLidarrBlock::Downloads)]
#[case(1, ActiveLidarrBlock::Artists, ActiveLidarrBlock::History)]
#[case(2, ActiveLidarrBlock::Downloads, ActiveLidarrBlock::RootFolders)]
#[case(3, ActiveLidarrBlock::History, ActiveLidarrBlock::Indexers)]
#[case(4, ActiveLidarrBlock::RootFolders, ActiveLidarrBlock::System)]
#[case(5, ActiveLidarrBlock::Indexers, ActiveLidarrBlock::Artists)]
#[case(1, ActiveLidarrBlock::Artists, ActiveLidarrBlock::Blocklist)]
#[case(2, ActiveLidarrBlock::Downloads, ActiveLidarrBlock::History)]
#[case(3, ActiveLidarrBlock::Blocklist, ActiveLidarrBlock::RootFolders)]
#[case(4, ActiveLidarrBlock::History, ActiveLidarrBlock::Indexers)]
#[case(5, ActiveLidarrBlock::RootFolders, ActiveLidarrBlock::System)]
#[case(6, ActiveLidarrBlock::Indexers, ActiveLidarrBlock::Artists)]
fn test_lidarr_handler_change_tab_left_right_keys_alt_navigation(
#[case] index: usize,
#[case] left_block: ActiveLidarrBlock,
@@ -122,10 +124,11 @@ mod tests {
#[rstest]
#[case(0, ActiveLidarrBlock::Artists)]
#[case(1, ActiveLidarrBlock::Downloads)]
#[case(2, ActiveLidarrBlock::History)]
#[case(3, ActiveLidarrBlock::RootFolders)]
#[case(4, ActiveLidarrBlock::Indexers)]
#[case(5, ActiveLidarrBlock::System)]
#[case(2, ActiveLidarrBlock::Blocklist)]
#[case(3, ActiveLidarrBlock::History)]
#[case(4, ActiveLidarrBlock::RootFolders)]
#[case(5, ActiveLidarrBlock::Indexers)]
#[case(6, ActiveLidarrBlock::System)]
fn test_lidarr_handler_change_tab_left_right_keys_alt_navigation_no_op_when_ignoring_quit_key(
#[case] index: usize,
#[case] block: ActiveLidarrBlock,
@@ -197,6 +200,24 @@ mod tests {
);
}
#[rstest]
fn test_delegates_blocklist_blocks_to_blocklist_handler(
#[values(
ActiveLidarrBlock::Blocklist,
ActiveLidarrBlock::BlocklistItemDetails,
ActiveLidarrBlock::DeleteBlocklistItemPrompt,
ActiveLidarrBlock::BlocklistClearAllItemsPrompt,
ActiveLidarrBlock::BlocklistSortPrompt
)]
active_lidarr_block: ActiveLidarrBlock,
) {
test_handler_delegation!(
LidarrHandler,
ActiveLidarrBlock::Blocklist,
active_lidarr_block
);
}
#[rstest]
fn test_delegates_history_blocks_to_history_handler(
#[values(
+5
View File
@@ -3,6 +3,7 @@ use indexers::IndexersHandler;
use library::LibraryHandler;
use super::KeyEventHandler;
use crate::handlers::lidarr_handlers::blocklist::BlocklistHandler;
use crate::handlers::lidarr_handlers::downloads::DownloadsHandler;
use crate::handlers::lidarr_handlers::root_folders::RootFoldersHandler;
use crate::handlers::lidarr_handlers::system::SystemHandler;
@@ -11,6 +12,7 @@ use crate::{
app::App, event::Key, matches_key, models::servarr_data::lidarr::lidarr_data::ActiveLidarrBlock,
};
mod blocklist;
mod downloads;
mod history;
mod indexers;
@@ -38,6 +40,9 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveLidarrBlock> for LidarrHandler<'a, 'b
_ if DownloadsHandler::accepts(self.active_lidarr_block) => {
DownloadsHandler::new(self.key, self.app, self.active_lidarr_block, self.context).handle();
}
_ if BlocklistHandler::accepts(self.active_lidarr_block) => {
BlocklistHandler::new(self.key, self.app, self.active_lidarr_block, self.context).handle();
}
_ if HistoryHandler::accepts(self.active_lidarr_block) => {
HistoryHandler::new(self.key, self.app, self.active_lidarr_block, self.context).handle();
}
@@ -505,19 +505,18 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveLidarrBlock> for AddRootFolderHandler
.tags
)
}
ActiveLidarrBlock::AddRootFolderPrompt => {
ActiveLidarrBlock::AddRootFolderPrompt
if self.app.data.lidarr_data.selected_block.get_active_block()
== ActiveLidarrBlock::AddRootFolderConfirmPrompt
&& matches_key!(confirm, key)
{
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action = Some(LidarrEvent::AddRootFolder(
self.build_add_root_folder_body(),
));
self.app.should_refresh = true;
&& matches_key!(confirm, key) =>
{
self.app.data.lidarr_data.prompt_confirm = true;
self.app.data.lidarr_data.prompt_confirm_action = Some(LidarrEvent::AddRootFolder(
self.build_add_root_folder_body(),
));
self.app.should_refresh = true;
self.app.pop_navigation_stack();
}
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -71,7 +71,7 @@ mod tests {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::RootFolders.into());
app.is_loading = is_ready;
app.data.lidarr_data.main_tabs.set_index(3);
app.data.lidarr_data.main_tabs.set_index(4);
RootFoldersHandler::new(
DEFAULT_KEYBINDINGS.left.key,
@@ -93,7 +93,7 @@ mod tests {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::RootFolders.into());
app.is_loading = is_ready;
app.data.lidarr_data.main_tabs.set_index(3);
app.data.lidarr_data.main_tabs.set_index(4);
RootFoldersHandler::new(
DEFAULT_KEYBINDINGS.right.key,
@@ -27,7 +27,7 @@ mod tests {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::System.into());
app.is_loading = is_ready;
app.data.lidarr_data.main_tabs.set_index(5);
app.data.lidarr_data.main_tabs.set_index(6);
SystemHandler::new(
DEFAULT_KEYBINDINGS.left.key,
@@ -49,7 +49,7 @@ mod tests {
let mut app = App::test_default();
app.push_navigation_stack(ActiveLidarrBlock::System.into());
app.is_loading = is_ready;
app.data.lidarr_data.main_tabs.set_index(5);
app.data.lidarr_data.main_tabs.set_index(6);
SystemHandler::new(
DEFAULT_KEYBINDINGS.right.key,
+4 -2
View File
@@ -116,6 +116,8 @@ pub fn handle_events(key: Key, app: &mut App<'_>) {
} else {
app.keymapping_table = None;
}
} else if matches_key!(esc, key) && app.notification.is_some() {
app.notification.take();
} else {
match app.get_current_route() {
_ if app.keymapping_table.is_some() => {
@@ -137,8 +139,8 @@ pub fn handle_events(key: Key, app: &mut App<'_>) {
pub fn populate_keymapping_table(app: &mut App<'_>) {
let context_clue_to_keybinding_item = |key: &KeyBinding, desc: &&str| {
let (key, alt_key) = if key.alt.is_some() {
(key.key.to_string(), key.alt.as_ref().unwrap().to_string())
let (key, alt_key) = if let Some(key1) = key.alt {
(key.key.to_string(), key1.to_string())
} else {
(key.key.to_string(), String::new())
};
@@ -354,19 +354,18 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveRadarrBlock> for EditCollectionHandle
.path
)
}
ActiveRadarrBlock::EditCollectionPrompt => {
ActiveRadarrBlock::EditCollectionPrompt
if self.app.data.radarr_data.selected_block.get_active_block()
== ActiveRadarrBlock::EditCollectionConfirmPrompt
&& matches_key!(confirm, key)
{
self.app.data.radarr_data.prompt_confirm = true;
self.app.data.radarr_data.prompt_confirm_action = Some(RadarrEvent::EditCollection(
self.build_edit_collection_params(),
));
self.app.should_refresh = true;
&& matches_key!(confirm, key) =>
{
self.app.data.radarr_data.prompt_confirm = true;
self.app.data.radarr_data.prompt_confirm_action = Some(RadarrEvent::EditCollection(
self.build_edit_collection_params(),
));
self.app.should_refresh = true;
self.app.pop_navigation_stack();
}
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -507,18 +507,17 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveRadarrBlock> for EditIndexerHandler<'
.tags
);
}
ActiveRadarrBlock::EditIndexerPrompt => {
ActiveRadarrBlock::EditIndexerPrompt
if self.app.data.radarr_data.selected_block.get_active_block()
== ActiveRadarrBlock::EditIndexerConfirmPrompt
&& matches_key!(confirm, self.key)
{
self.app.data.radarr_data.prompt_confirm = true;
self.app.data.radarr_data.prompt_confirm_action =
Some(RadarrEvent::EditIndexer(self.build_edit_indexer_params()));
self.app.should_refresh = true;
&& matches_key!(confirm, self.key) =>
{
self.app.data.radarr_data.prompt_confirm = true;
self.app.data.radarr_data.prompt_confirm_action =
Some(RadarrEvent::EditIndexer(self.build_edit_indexer_params()));
self.app.should_refresh = true;
self.app.pop_navigation_stack();
}
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -114,10 +114,10 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveRadarrBlock> for IndexerSettingsHandl
ActiveRadarrBlock::IndexerSettingsAvailabilityDelayInput => {
indexer_settings.availability_delay -= 1;
}
ActiveRadarrBlock::IndexerSettingsRssSyncIntervalInput => {
if indexer_settings.rss_sync_interval > 0 {
indexer_settings.rss_sync_interval -= 1;
}
ActiveRadarrBlock::IndexerSettingsRssSyncIntervalInput
if indexer_settings.rss_sync_interval > 0 =>
{
indexer_settings.rss_sync_interval -= 1;
}
_ => (),
}
@@ -272,19 +272,18 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveRadarrBlock> for IndexerSettingsHandl
.whitelisted_hardcoded_subs
)
}
ActiveRadarrBlock::AllIndexerSettingsPrompt => {
ActiveRadarrBlock::AllIndexerSettingsPrompt
if self.app.data.radarr_data.selected_block.get_active_block()
== ActiveRadarrBlock::IndexerSettingsConfirmPrompt
&& matches_key!(confirm, self.key)
{
self.app.data.radarr_data.prompt_confirm = true;
self.app.data.radarr_data.prompt_confirm_action = Some(
RadarrEvent::EditAllIndexerSettings(self.build_edit_indexer_settings_body()),
);
self.app.should_refresh = true;
&& matches_key!(confirm, self.key) =>
{
self.app.data.radarr_data.prompt_confirm = true;
self.app.data.radarr_data.prompt_confirm_action = Some(
RadarrEvent::EditAllIndexerSettings(self.build_edit_indexer_settings_body()),
);
self.app.should_refresh = true;
self.app.pop_navigation_stack();
}
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -539,16 +539,15 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveRadarrBlock> for AddMovieHandler<'a,
.tags
)
}
ActiveRadarrBlock::AddMoviePrompt => {
ActiveRadarrBlock::AddMoviePrompt
if self.app.data.radarr_data.selected_block.get_active_block()
== ActiveRadarrBlock::AddMovieConfirmPrompt
&& matches_key!(confirm, key)
{
self.app.data.radarr_data.prompt_confirm = true;
self.app.data.radarr_data.prompt_confirm_action =
Some(RadarrEvent::AddMovie(self.build_add_movie_body()));
self.app.pop_navigation_stack();
}
&& matches_key!(confirm, key) =>
{
self.app.data.radarr_data.prompt_confirm = true;
self.app.data.radarr_data.prompt_confirm_action =
Some(RadarrEvent::AddMovie(self.build_add_movie_body()));
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -376,18 +376,17 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveRadarrBlock> for EditMovieHandler<'a,
.tags
)
}
ActiveRadarrBlock::EditMoviePrompt => {
ActiveRadarrBlock::EditMoviePrompt
if self.app.data.radarr_data.selected_block.get_active_block()
== ActiveRadarrBlock::EditMovieConfirmPrompt
&& matches_key!(confirm, key)
{
self.app.data.radarr_data.prompt_confirm = true;
self.app.data.radarr_data.prompt_confirm_action =
Some(RadarrEvent::EditMovie(self.build_edit_movie_params()));
self.app.should_refresh = true;
&& matches_key!(confirm, key) =>
{
self.app.data.radarr_data.prompt_confirm = true;
self.app.data.radarr_data.prompt_confirm_action =
Some(RadarrEvent::EditMovie(self.build_edit_movie_params()));
self.app.should_refresh = true;
self.app.pop_navigation_stack();
}
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -506,18 +506,17 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveSonarrBlock> for EditIndexerHandler<'
.tags
);
}
ActiveSonarrBlock::EditIndexerPrompt => {
ActiveSonarrBlock::EditIndexerPrompt
if self.app.data.sonarr_data.selected_block.get_active_block()
== ActiveSonarrBlock::EditIndexerConfirmPrompt
&& matches_key!(confirm, self.key)
{
self.app.data.sonarr_data.prompt_confirm = true;
self.app.data.sonarr_data.prompt_confirm_action =
Some(SonarrEvent::EditIndexer(self.build_edit_indexer_params()));
self.app.should_refresh = true;
&& matches_key!(confirm, self.key) =>
{
self.app.data.sonarr_data.prompt_confirm = true;
self.app.data.sonarr_data.prompt_confirm_action =
Some(SonarrEvent::EditIndexer(self.build_edit_indexer_params()));
self.app.should_refresh = true;
self.app.pop_navigation_stack();
}
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -106,10 +106,10 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveSonarrBlock> for IndexerSettingsHandl
indexer_settings.maximum_size -= 1;
}
}
ActiveSonarrBlock::IndexerSettingsRssSyncIntervalInput => {
if indexer_settings.rss_sync_interval > 0 {
indexer_settings.rss_sync_interval -= 1;
}
ActiveSonarrBlock::IndexerSettingsRssSyncIntervalInput
if indexer_settings.rss_sync_interval > 0 =>
{
indexer_settings.rss_sync_interval -= 1;
}
_ => (),
}
@@ -606,16 +606,15 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveSonarrBlock> for AddSeriesHandler<'a,
.tags
)
}
ActiveSonarrBlock::AddSeriesPrompt => {
ActiveSonarrBlock::AddSeriesPrompt
if self.app.data.sonarr_data.selected_block.get_active_block()
== ActiveSonarrBlock::AddSeriesConfirmPrompt
&& matches_key!(confirm, key)
{
self.app.data.sonarr_data.prompt_confirm = true;
self.app.data.sonarr_data.prompt_confirm_action =
Some(SonarrEvent::AddSeries(self.build_add_series_body()));
self.app.pop_navigation_stack();
}
&& matches_key!(confirm, key) =>
{
self.app.data.sonarr_data.prompt_confirm = true;
self.app.data.sonarr_data.prompt_confirm_action =
Some(SonarrEvent::AddSeries(self.build_add_series_body()));
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -450,18 +450,17 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveSonarrBlock> for EditSeriesHandler<'a
.tags
)
}
ActiveSonarrBlock::EditSeriesPrompt => {
ActiveSonarrBlock::EditSeriesPrompt
if self.app.data.sonarr_data.selected_block.get_active_block()
== ActiveSonarrBlock::EditSeriesConfirmPrompt
&& matches_key!(confirm, key)
{
self.app.data.sonarr_data.prompt_confirm = true;
self.app.data.sonarr_data.prompt_confirm_action =
Some(SonarrEvent::EditSeries(self.build_edit_series_params()));
self.app.should_refresh = true;
&& matches_key!(confirm, key) =>
{
self.app.data.sonarr_data.prompt_confirm = true;
self.app.data.sonarr_data.prompt_confirm_action =
Some(SonarrEvent::EditSeries(self.build_edit_series_params()));
self.app.should_refresh = true;
self.app.pop_navigation_stack();
}
self.app.pop_navigation_stack();
}
_ => (),
}
@@ -279,8 +279,9 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveSonarrBlock> for SeasonDetailsHandler
}
ActiveSonarrBlock::AutomaticallySearchSeasonPrompt => {
if self.app.data.sonarr_data.prompt_confirm {
let (series_id, season_number) = self.extract_series_id_season_number_tuple();
self.app.data.sonarr_data.prompt_confirm_action = Some(
SonarrEvent::TriggerAutomaticSeasonSearch(self.extract_series_id_season_number_tuple()),
SonarrEvent::TriggerAutomaticSeasonSearch(series_id, season_number),
);
}
@@ -404,8 +405,9 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveSonarrBlock> for SeasonDetailsHandler
},
ActiveSonarrBlock::AutomaticallySearchSeasonPrompt if matches_key!(confirm, key) => {
self.app.data.sonarr_data.prompt_confirm = true;
let (series_id, season_number) = self.extract_series_id_season_number_tuple();
self.app.data.sonarr_data.prompt_confirm_action = Some(
SonarrEvent::TriggerAutomaticSeasonSearch(self.extract_series_id_season_number_tuple()),
SonarrEvent::TriggerAutomaticSeasonSearch(series_id, season_number),
);
self.app.pop_navigation_stack();
@@ -268,7 +268,7 @@ mod tests {
#[rstest]
#[case(
ActiveSonarrBlock::AutomaticallySearchSeasonPrompt,
SonarrEvent::TriggerAutomaticSeasonSearch((0, 0))
SonarrEvent::TriggerAutomaticSeasonSearch(0, 0)
)]
#[case(
ActiveSonarrBlock::DeleteEpisodeFilePrompt,
@@ -694,7 +694,7 @@ mod tests {
#[rstest]
#[case(
ActiveSonarrBlock::AutomaticallySearchSeasonPrompt,
SonarrEvent::TriggerAutomaticSeasonSearch((0, 0))
SonarrEvent::TriggerAutomaticSeasonSearch(0, 0)
)]
#[case(
ActiveSonarrBlock::DeleteEpisodeFilePrompt,
@@ -278,8 +278,9 @@ impl<'a, 'b> KeyEventHandler<'a, 'b, ActiveSonarrBlock> for SeriesDetailsHandler
}
_ if matches_key!(toggle_monitoring, key) => {
self.app.data.sonarr_data.prompt_confirm = true;
let (series_id, season_number) = self.extract_series_id_season_number_tuple();
self.app.data.sonarr_data.prompt_confirm_action = Some(
SonarrEvent::ToggleSeasonMonitoring(self.extract_series_id_season_number_tuple()),
SonarrEvent::ToggleSeasonMonitoring(series_id, season_number),
);
self
@@ -378,7 +378,7 @@ mod tests {
assert!(app.is_routing);
assert_some_eq_x!(
&app.data.sonarr_data.prompt_confirm_action,
&SonarrEvent::ToggleSeasonMonitoring((0, 0))
&SonarrEvent::ToggleSeasonMonitoring(0, 0)
);
}
+1 -1
View File
@@ -893,7 +893,7 @@ mod tests {
app.push_navigation_stack(ActiveRadarrBlock::MoviesSortPrompt.into());
let mut expected_vec = movies_vec();
expected_vec.sort_by(|a, b| a.id.cmp(&b.id));
expected_vec.sort_by_key(|a| a.id);
expected_vec.reverse();
TableHandlerUnit::new(
-2
View File
@@ -36,8 +36,6 @@ pub const READARR_LOGO: &str = "⠀⣀⣠⣤⣄⣀⠀
";
// Allowing this code for now since we'll eventually be implementing additional Servarr support and we'll need it then
#[allow(dead_code)]
pub const LIDARR_LOGO: &str = "⠀⣠⣴⣶⡿⠻⣿⣶⣦⣄⠀
+26 -6
View File
@@ -2,7 +2,7 @@
#[macro_use]
extern crate assertables;
use anyhow::Result;
use anyhow::{Context, Result};
use clap::{
Args, CommandFactory, Parser, crate_authors, crate_description, crate_name, crate_version,
};
@@ -86,7 +86,7 @@ struct GlobalOpts {
global = true,
value_parser,
env = "MANAGARR_CONFIG_FILE",
help = "The Managarr configuration file to use"
help = "The Managarr configuration file to use; defaults to the path shown by 'managarr config-path'"
)]
config_file: Option<PathBuf>,
#[arg(
@@ -127,15 +127,30 @@ async fn main() -> Result<()> {
let running = Arc::new(AtomicBool::new(true));
let r = running.clone();
let args = Cli::parse();
let mut config = if let Some(ref config_file) = args.global.config_file {
load_config(config_file.to_str().expect("Invalid config file specified"))?
let config_file_path = confy::get_configuration_file_path("managarr", "config")?;
let default_config_path = config_file_path.display().to_string();
if matches!(args.command, Some(Command::ConfigPath)) {
println!("{default_config_path}");
return Ok(());
}
let (mut config, config_path) = if let Some(ref config_file) = args.global.config_file {
(
load_config(config_file.to_str().expect("Invalid config file specified"))?,
config_file.display().to_string(),
)
} else {
confy::load("managarr", "config")?
(
confy::load("managarr", "config")
.with_context(|| format!("Config file at '{default_config_path}' is invalid"))?,
default_config_path,
)
};
let theme_name = config.theme.clone();
let spinner_disabled = args.global.disable_spinner;
debug!("Managarr loaded using config: {config:?}");
config.validate();
config.validate(&config_path);
config.post_process_initialization();
let reqwest_client = build_network_client(&config);
@@ -170,6 +185,11 @@ async fn main() -> Result<()> {
generate(shell, &mut cli, "managarr", &mut io::stdout())
}
Command::TailLogs { no_color } => tail_logs(no_color).await?,
Command::ConfigPath => {
unreachable!(
"ConfigPath command is handled before this match and should be unreachable here"
);
}
},
None => {
let app_nw = Arc::clone(&app);
+23
View File
@@ -499,6 +499,28 @@ pub struct LidarrReleaseDownloadBody {
pub indexer_id: i64,
}
#[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct BlocklistItem {
#[serde(deserialize_with = "super::from_i64")]
pub id: i64,
#[serde(deserialize_with = "super::from_i64")]
pub artist_id: i64,
pub album_ids: Option<Vec<Number>>,
pub source_title: String,
pub quality: QualityWrapper,
pub date: DateTime<Utc>,
pub protocol: String,
pub indexer: String,
pub message: String,
pub artist: Artist,
}
#[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct BlocklistResponse {
pub records: Vec<BlocklistItem>,
}
#[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct TrackFile {
@@ -574,6 +596,7 @@ serde_enum_from!(
Album(Album),
Artist(Artist),
Artists(Vec<Artist>),
BlocklistResponse(BlocklistResponse),
DiskSpaces(Vec<DiskSpace>),
DownloadsResponse(DownloadsResponse),
LidarrHistoryWrapper(LidarrHistoryWrapper),
+22 -4
View File
@@ -5,10 +5,10 @@ mod tests {
use serde_json::json;
use crate::models::lidarr_models::{
AddArtistSearchResult, Album, AudioTags, DownloadRecord, DownloadStatus, DownloadsResponse,
LidarrHistoryEventType, LidarrHistoryItem, LidarrHistoryWrapper, LidarrRelease, LidarrTask,
MediaInfo, Member, MetadataProfile, MonitorType, NewItemMonitorType, SystemStatus, Track,
TrackFile,
AddArtistSearchResult, Album, AudioTags, BlocklistItem, BlocklistResponse, DownloadRecord,
DownloadStatus, DownloadsResponse, LidarrHistoryEventType, LidarrHistoryItem,
LidarrHistoryWrapper, LidarrRelease, LidarrTask, MediaInfo, Member, MetadataProfile,
MonitorType, NewItemMonitorType, SystemStatus, Track, TrackFile,
};
use crate::models::servarr_models::{
DiskSpace, HostConfig, Indexer, IndexerSettings, IndexerTestResult, Log, LogResponse,
@@ -276,9 +276,27 @@ mod tests {
assert_eq!(lidarr_serdeable, LidarrSerdeable::Artist(artist));
}
#[test]
fn test_lidarr_serdeable_from_blocklist_response() {
let blocklist_response = BlocklistResponse {
records: vec![BlocklistItem {
id: 1,
..BlocklistItem::default()
}],
};
let lidarr_serdeable: LidarrSerdeable = blocklist_response.clone().into();
assert_eq!(
lidarr_serdeable,
LidarrSerdeable::BlocklistResponse(blocklist_response)
);
}
#[test]
fn test_lidarr_serdeable_from_disk_spaces() {
let disk_spaces = vec![DiskSpace {
path: Some("/path".to_owned()),
free_space: 1,
total_space: 1,
}];
+1
View File
@@ -233,6 +233,7 @@ mod tests {
#[test]
fn test_radarr_serdeable_from_disk_spaces() {
let disk_spaces = vec![DiskSpace {
path: Some("/path".to_owned()),
free_space: 1,
total_space: 1,
}];
+30 -4
View File
@@ -2,14 +2,14 @@ use serde_json::Number;
use super::modals::{AddArtistModal, AddRootFolderModal, AlbumDetailsModal, EditArtistModal};
use crate::app::context_clues::{
DOWNLOADS_CONTEXT_CLUES, HISTORY_CONTEXT_CLUES, INDEXERS_CONTEXT_CLUES,
BLOCKLIST_CONTEXT_CLUES, DOWNLOADS_CONTEXT_CLUES, HISTORY_CONTEXT_CLUES, INDEXERS_CONTEXT_CLUES,
ROOT_FOLDERS_CONTEXT_CLUES, SYSTEM_CONTEXT_CLUES,
};
use crate::app::lidarr::lidarr_context_clues::{
ARTIST_DETAILS_CONTEXT_CLUES, ARTIST_HISTORY_CONTEXT_CLUES, ARTISTS_CONTEXT_CLUES,
MANUAL_ARTIST_SEARCH_CONTEXT_CLUES,
};
use crate::models::lidarr_models::{LidarrRelease, LidarrTask};
use crate::models::lidarr_models::{BlocklistItem, LidarrRelease, LidarrTask};
use crate::models::servarr_data::modals::EditIndexerModal;
use crate::models::servarr_models::{IndexerSettings, QueueEvent};
use crate::models::stateful_list::StatefulList;
@@ -30,6 +30,7 @@ use {
super::modals::TrackDetailsModal,
crate::models::lidarr_models::{MonitorType, NewItemMonitorType},
crate::models::stateful_table::SortOption,
crate::network::lidarr_network::lidarr_network_test_utils::test_utils::blocklist_item,
crate::network::lidarr_network::lidarr_network_test_utils::test_utils::indexer_settings,
crate::network::lidarr_network::lidarr_network_test_utils::test_utils::quality_profile_map,
crate::network::lidarr_network::lidarr_network_test_utils::test_utils::{
@@ -64,6 +65,7 @@ pub struct LidarrData<'a> {
pub artist_history: StatefulTable<LidarrHistoryItem>,
pub artist_info_tabs: TabState,
pub artists: StatefulTable<Artist>,
pub blocklist: StatefulTable<BlocklistItem>,
pub delete_files: bool,
pub discography_releases: StatefulTable<LidarrRelease>,
pub disk_space_vec: Vec<DiskSpace>,
@@ -149,6 +151,7 @@ impl<'a> Default for LidarrData<'a> {
album_details_modal: None,
artist_history: StatefulTable::default(),
artists: StatefulTable::default(),
blocklist: StatefulTable::default(),
delete_files: false,
discography_releases: StatefulTable::default(),
disk_space_vec: Vec::new(),
@@ -187,6 +190,12 @@ impl<'a> Default for LidarrData<'a> {
contextual_help: Some(&DOWNLOADS_CONTEXT_CLUES),
config: None,
},
TabRoute {
title: "Blocklist".to_string(),
route: ActiveLidarrBlock::Blocklist.into(),
contextual_help: Some(&BLOCKLIST_CONTEXT_CLUES),
config: None,
},
TabRoute {
title: "History".to_string(),
route: ActiveLidarrBlock::History.into(),
@@ -293,8 +302,10 @@ impl LidarrData<'_> {
.metadata_profile_list
.set_items(vec![metadata_profile().name]);
let mut track_details_modal = TrackDetailsModal::default();
track_details_modal.track_details = ScrollableText::with_string("Some details".to_owned());
let mut track_details_modal = TrackDetailsModal {
track_details: ScrollableText::with_string("Some details".to_owned()),
..TrackDetailsModal::default()
};
track_details_modal
.track_history
.set_items(vec![lidarr_history_item()]);
@@ -377,6 +388,8 @@ impl LidarrData<'_> {
}]);
lidarr_data.artists.search = Some("artist search".into());
lidarr_data.artists.filter = Some("artist filter".into());
lidarr_data.blocklist.set_items(vec![blocklist_item()]);
lidarr_data.blocklist.sorting(vec![sort_option!(id)]);
lidarr_data.downloads.set_items(vec![download_record()]);
lidarr_data.history.set_items(vec![lidarr_history_item()]);
lidarr_data.history.sorting(vec![SortOption {
@@ -444,6 +457,11 @@ pub enum ActiveLidarrBlock {
AllIndexerSettingsPrompt,
AutomaticallySearchAlbumPrompt,
AutomaticallySearchArtistPrompt,
Blocklist,
BlocklistItemDetails,
DeleteBlocklistItemPrompt,
BlocklistClearAllItemsPrompt,
BlocklistSortPrompt,
DeleteAlbumPrompt,
DeleteAlbumConfirmPrompt,
DeleteAlbumToggleDeleteFile,
@@ -579,6 +597,14 @@ pub static ALBUM_DETAILS_BLOCKS: [ActiveLidarrBlock; 15] = [
ActiveLidarrBlock::DeleteTrackFilePrompt,
];
pub static BLOCKLIST_BLOCKS: [ActiveLidarrBlock; 5] = [
ActiveLidarrBlock::Blocklist,
ActiveLidarrBlock::BlocklistItemDetails,
ActiveLidarrBlock::DeleteBlocklistItemPrompt,
ActiveLidarrBlock::BlocklistClearAllItemsPrompt,
ActiveLidarrBlock::BlocklistSortPrompt,
];
pub static DOWNLOADS_BLOCKS: [ActiveLidarrBlock; 3] = [
ActiveLidarrBlock::Downloads,
ActiveLidarrBlock::DeleteDownloadPrompt,
@@ -1,8 +1,8 @@
#[cfg(test)]
mod tests {
use crate::app::context_clues::{
DOWNLOADS_CONTEXT_CLUES, HISTORY_CONTEXT_CLUES, INDEXERS_CONTEXT_CLUES,
ROOT_FOLDERS_CONTEXT_CLUES, SYSTEM_CONTEXT_CLUES,
BLOCKLIST_CONTEXT_CLUES, DOWNLOADS_CONTEXT_CLUES, HISTORY_CONTEXT_CLUES,
INDEXERS_CONTEXT_CLUES, ROOT_FOLDERS_CONTEXT_CLUES, SYSTEM_CONTEXT_CLUES,
};
use crate::app::lidarr::lidarr_context_clues::{
ARTIST_DETAILS_CONTEXT_CLUES, ARTIST_HISTORY_CONTEXT_CLUES, ARTISTS_CONTEXT_CLUES,
@@ -11,7 +11,7 @@ mod tests {
use crate::models::lidarr_models::{Album, LidarrHistoryItem, LidarrRelease};
use crate::models::servarr_data::lidarr::lidarr_data::{
ADD_ARTIST_BLOCKS, ADD_ARTIST_SELECTION_BLOCKS, ADD_ROOT_FOLDER_BLOCKS, ALBUM_DETAILS_BLOCKS,
ARTIST_DETAILS_BLOCKS, DELETE_ALBUM_BLOCKS, DELETE_ALBUM_SELECTION_BLOCKS,
ARTIST_DETAILS_BLOCKS, BLOCKLIST_BLOCKS, DELETE_ALBUM_BLOCKS, DELETE_ALBUM_SELECTION_BLOCKS,
DELETE_ARTIST_BLOCKS, DELETE_ARTIST_SELECTION_BLOCKS, DOWNLOADS_BLOCKS, EDIT_ARTIST_BLOCKS,
EDIT_ARTIST_SELECTION_BLOCKS, EDIT_INDEXER_BLOCKS, EDIT_INDEXER_NZB_SELECTION_BLOCKS,
EDIT_INDEXER_TORRENT_SELECTION_BLOCKS, HISTORY_BLOCKS, INDEXER_SETTINGS_BLOCKS,
@@ -149,6 +149,7 @@ mod tests {
assert_none!(lidarr_data.album_details_modal);
assert_is_empty!(lidarr_data.artists);
assert_is_empty!(lidarr_data.artist_history);
assert_is_empty!(lidarr_data.blocklist);
assert!(!lidarr_data.delete_files);
assert_is_empty!(lidarr_data.disk_space_vec);
assert_is_empty!(lidarr_data.downloads);
@@ -171,7 +172,7 @@ mod tests {
assert_is_empty!(lidarr_data.updates);
assert_is_empty!(lidarr_data.version);
assert_eq!(lidarr_data.main_tabs.tabs.len(), 6);
assert_eq!(lidarr_data.main_tabs.tabs.len(), 7);
assert_str_eq!(lidarr_data.main_tabs.tabs[0].title, "Library");
assert_eq!(
@@ -195,50 +196,61 @@ mod tests {
);
assert_none!(lidarr_data.main_tabs.tabs[1].config);
assert_str_eq!(lidarr_data.main_tabs.tabs[2].title, "History");
assert_str_eq!(lidarr_data.main_tabs.tabs[2].title, "Blocklist");
assert_eq!(
lidarr_data.main_tabs.tabs[2].route,
ActiveLidarrBlock::History.into()
ActiveLidarrBlock::Blocklist.into()
);
assert_some_eq_x!(
&lidarr_data.main_tabs.tabs[2].contextual_help,
&HISTORY_CONTEXT_CLUES
&BLOCKLIST_CONTEXT_CLUES
);
assert_none!(lidarr_data.main_tabs.tabs[2].config);
assert_str_eq!(lidarr_data.main_tabs.tabs[3].title, "Root Folders");
assert_str_eq!(lidarr_data.main_tabs.tabs[3].title, "History");
assert_eq!(
lidarr_data.main_tabs.tabs[3].route,
ActiveLidarrBlock::RootFolders.into()
ActiveLidarrBlock::History.into()
);
assert_some_eq_x!(
&lidarr_data.main_tabs.tabs[3].contextual_help,
&ROOT_FOLDERS_CONTEXT_CLUES
&HISTORY_CONTEXT_CLUES
);
assert_none!(lidarr_data.main_tabs.tabs[3].config);
assert_str_eq!(lidarr_data.main_tabs.tabs[4].title, "Indexers");
assert_str_eq!(lidarr_data.main_tabs.tabs[4].title, "Root Folders");
assert_eq!(
lidarr_data.main_tabs.tabs[4].route,
ActiveLidarrBlock::Indexers.into()
ActiveLidarrBlock::RootFolders.into()
);
assert_some_eq_x!(
&lidarr_data.main_tabs.tabs[4].contextual_help,
&INDEXERS_CONTEXT_CLUES
&ROOT_FOLDERS_CONTEXT_CLUES
);
assert_none!(lidarr_data.main_tabs.tabs[4].config);
assert_str_eq!(lidarr_data.main_tabs.tabs[5].title, "System");
assert_str_eq!(lidarr_data.main_tabs.tabs[5].title, "Indexers");
assert_eq!(
lidarr_data.main_tabs.tabs[5].route,
ActiveLidarrBlock::System.into()
ActiveLidarrBlock::Indexers.into()
);
assert_some_eq_x!(
&lidarr_data.main_tabs.tabs[5].contextual_help,
&SYSTEM_CONTEXT_CLUES
&INDEXERS_CONTEXT_CLUES
);
assert_none!(lidarr_data.main_tabs.tabs[5].config);
assert_str_eq!(lidarr_data.main_tabs.tabs[6].title, "System");
assert_eq!(
lidarr_data.main_tabs.tabs[6].route,
ActiveLidarrBlock::System.into()
);
assert_some_eq_x!(
&lidarr_data.main_tabs.tabs[6].contextual_help,
&SYSTEM_CONTEXT_CLUES
);
assert_none!(lidarr_data.main_tabs.tabs[6].config);
assert_eq!(lidarr_data.artist_info_tabs.tabs.len(), 3);
assert_str_eq!(lidarr_data.artist_info_tabs.tabs[0].title, "Albums");
assert_eq!(
@@ -326,6 +338,16 @@ mod tests {
assert!(ALBUM_DETAILS_BLOCKS.contains(&ActiveLidarrBlock::DeleteTrackFilePrompt));
}
#[test]
fn test_blocklist_blocks_contents() {
assert_eq!(BLOCKLIST_BLOCKS.len(), 5);
assert!(BLOCKLIST_BLOCKS.contains(&ActiveLidarrBlock::Blocklist));
assert!(BLOCKLIST_BLOCKS.contains(&ActiveLidarrBlock::BlocklistItemDetails));
assert!(BLOCKLIST_BLOCKS.contains(&ActiveLidarrBlock::DeleteBlocklistItemPrompt));
assert!(BLOCKLIST_BLOCKS.contains(&ActiveLidarrBlock::BlocklistClearAllItemsPrompt));
assert!(BLOCKLIST_BLOCKS.contains(&ActiveLidarrBlock::BlocklistSortPrompt));
}
#[test]
fn test_downloads_blocks_contains_expected_blocks() {
assert_eq!(DOWNLOADS_BLOCKS.len(), 3);
+17
View File
@@ -10,6 +10,23 @@ pub(in crate::models::servarr_data) mod data_test_utils;
#[cfg(test)]
mod servarr_data_tests;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Notification {
pub title: String,
pub message: String,
pub success: bool,
}
impl Notification {
pub fn new(title: String, message: String, success: bool) -> Self {
Self {
title,
message,
success,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum ActiveKeybindingBlock {
#[default]
+1
View File
@@ -83,6 +83,7 @@ pub struct CommandBody {
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DiskSpace {
pub path: Option<String>,
#[serde(deserialize_with = "super::from_i64")]
pub free_space: i64,
#[serde(deserialize_with = "super::from_i64")]
+1
View File
@@ -427,6 +427,7 @@ mod tests {
#[test]
fn test_sonarr_serdeable_from_disk_spaces() {
let disk_spaces = vec![DiskSpace {
path: Some("/path".to_owned()),
free_space: 1,
total_space: 1,
}];
@@ -0,0 +1,353 @@
#[cfg(test)]
mod tests {
use crate::models::lidarr_models::{Artist, BlocklistItem, BlocklistResponse, LidarrSerdeable};
use crate::models::servarr_data::lidarr::lidarr_data::ActiveLidarrBlock;
use crate::models::stateful_table::SortOption;
use crate::network::lidarr_network::LidarrEvent;
use crate::network::lidarr_network::lidarr_network_test_utils::test_utils::{
artist, blocklist_item,
};
use crate::network::network_tests::test_utils::{MockServarrApi, test_network};
use pretty_assertions::assert_eq;
use rstest::rstest;
use serde_json::{Number, json};
#[tokio::test]
async fn test_handle_clear_lidarr_blocklist_event() {
let blocklist_items = vec![
BlocklistItem {
id: 1,
..blocklist_item()
},
BlocklistItem {
id: 2,
..blocklist_item()
},
BlocklistItem {
id: 3,
..blocklist_item()
},
];
let expected_request_json = json!({ "ids": [1, 2, 3]});
let (mock, app, _server) = MockServarrApi::delete()
.with_request_body(expected_request_json)
.build_for(LidarrEvent::ClearBlocklist)
.await;
app
.lock()
.await
.data
.lidarr_data
.blocklist
.set_items(blocklist_items);
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
assert!(
network
.handle_lidarr_event(LidarrEvent::ClearBlocklist)
.await
.is_ok()
);
mock.assert_async().await;
}
#[tokio::test]
async fn test_handle_delete_lidarr_blocklist_item_event() {
let (mock, app, _server) = MockServarrApi::delete()
.path("/1")
.build_for(LidarrEvent::DeleteBlocklistItem(1))
.await;
app
.lock()
.await
.data
.lidarr_data
.blocklist
.set_items(vec![blocklist_item()]);
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
assert!(
network
.handle_lidarr_event(LidarrEvent::DeleteBlocklistItem(1))
.await
.is_ok()
);
mock.assert_async().await;
}
#[rstest]
#[tokio::test]
async fn test_handle_get_lidarr_blocklist_event(#[values(true, false)] use_custom_sorting: bool) {
let blocklist_json = json!({"records": [{
"artistId": 1007,
"albumIds": [42020],
"sourceTitle": "z artist",
"quality": { "quality": { "name": "Lossless" }},
"date": "2023-05-20T21:29:16Z",
"protocol": "usenet",
"indexer": "NZBgeek (Prowlarr)",
"message": "test message",
"id": 123,
"artist": {
"id": 1,
"artistName": "Alex",
"foreignArtistId": "test-foreign-id",
"status": "continuing",
"overview": "some interesting description of the artist",
"artistType": "Person",
"disambiguation": "American pianist",
"path": "/nfs/music/test-artist",
"members": [{"name": "alex", "instrument": "piano"}],
"qualityProfileId": 1,
"metadataProfileId": 1,
"monitored": true,
"monitorNewItems": "all",
"genres": ["soundtrack"],
"tags": [1],
"added": "2023-01-01T00:00:00Z",
"ratings": { "votes": 15, "value": 8.4 },
"statistics": {
"albumCount": 1,
"trackFileCount": 15,
"trackCount": 15,
"totalTrackCount": 15,
"sizeOnDisk": 12345,
"percentOfTracks": 99.9
}
}
},
{
"artistId": 2001,
"artistTitle": "Test Artist",
"albumIds": [42018],
"sourceTitle": "A Artist",
"quality": { "quality": { "name": "Lossless" }},
"date": "2023-05-20T21:29:16Z",
"protocol": "usenet",
"indexer": "NZBgeek (Prowlarr)",
"message": "test message",
"id": 456,
"artist": {
"id": 1,
"artistName": "Alex",
"foreignArtistId": "test-foreign-id",
"status": "continuing",
"overview": "some interesting description of the artist",
"artistType": "Person",
"disambiguation": "American pianist",
"path": "/nfs/music/test-artist",
"members": [{"name": "alex", "instrument": "piano"}],
"qualityProfileId": 1,
"metadataProfileId": 1,
"monitored": true,
"monitorNewItems": "all",
"genres": ["soundtrack"],
"tags": [1],
"added": "2023-01-01T00:00:00Z",
"ratings": { "votes": 15, "value": 8.4 },
"statistics": {
"albumCount": 1,
"trackFileCount": 15,
"trackCount": 15,
"totalTrackCount": 15,
"sizeOnDisk": 12345,
"percentOfTracks": 99.9
}
}
}]});
let response: BlocklistResponse = serde_json::from_value(blocklist_json.clone()).unwrap();
let mut expected_blocklist = vec![
BlocklistItem {
id: 123,
artist_id: 1007,
source_title: "z artist".into(),
album_ids: Some(vec![Number::from(42020)]),
..blocklist_item()
},
BlocklistItem {
id: 456,
artist_id: 2001,
source_title: "A Artist".into(),
album_ids: Some(vec![Number::from(42018)]),
..blocklist_item()
},
];
let (mock, app, _server) = MockServarrApi::get()
.returns(blocklist_json)
.build_for(LidarrEvent::GetBlocklist)
.await;
app
.lock()
.await
.data
.lidarr_data
.artists
.set_items(vec![Artist {
id: 1007,
artist_name: "Z Artist".into(),
..artist()
}]);
app.lock().await.data.lidarr_data.blocklist.sort_asc = true;
if use_custom_sorting {
let cmp_fn = |a: &BlocklistItem, b: &BlocklistItem| {
a.source_title
.to_lowercase()
.cmp(&b.source_title.to_lowercase())
};
expected_blocklist.sort_by(cmp_fn);
let blocklist_sort_option = SortOption {
name: "Source Title",
cmp_fn: Some(cmp_fn),
};
app
.lock()
.await
.data
.lidarr_data
.blocklist
.sorting(vec![blocklist_sort_option]);
}
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
let LidarrSerdeable::BlocklistResponse(blocklist) = network
.handle_lidarr_event(LidarrEvent::GetBlocklist)
.await
.unwrap()
else {
panic!("Expected BlocklistResponse")
};
mock.assert_async().await;
assert_eq!(
app.lock().await.data.lidarr_data.blocklist.items,
expected_blocklist
);
assert!(app.lock().await.data.lidarr_data.blocklist.sort_asc);
assert_eq!(blocklist, response);
}
#[tokio::test]
async fn test_handle_get_lidarr_blocklist_event_no_op_when_user_is_selecting_sort_options() {
let blocklist_json = json!({"records": [{
"artistId": 1007,
"albumIds": [42020],
"sourceTitle": "z artist",
"quality": { "quality": { "name": "Lossless" }},
"date": "2023-05-20T21:29:16Z",
"protocol": "usenet",
"indexer": "NZBgeek (Prowlarr)",
"message": "test message",
"id": 123,
"artist": {
"id": 1,
"artistName": "Alex",
"foreignArtistId": "test-foreign-id",
"status": "continuing",
"overview": "some interesting description of the artist",
"artistType": "Person",
"disambiguation": "American pianist",
"path": "/nfs/music/test-artist",
"members": [{"name": "alex", "instrument": "piano"}],
"qualityProfileId": 1,
"metadataProfileId": 1,
"monitored": true,
"monitorNewItems": "all",
"genres": ["soundtrack"],
"tags": [1],
"added": "2023-01-01T00:00:00Z",
"ratings": { "votes": 15, "value": 8.4 },
"statistics": {
"albumCount": 1,
"trackFileCount": 15,
"trackCount": 15,
"totalTrackCount": 15,
"sizeOnDisk": 12345,
"percentOfTracks": 99.9
}
}
},
{
"artistId": 2001,
"albumIds": [42018],
"sourceTitle": "A Artist",
"quality": { "quality": { "name": "Lossless" }},
"date": "2023-05-20T21:29:16Z",
"protocol": "usenet",
"indexer": "NZBgeek (Prowlarr)",
"message": "test message",
"id": 456,
"artist": {
"id": 1,
"artistName": "Alex",
"foreignArtistId": "test-foreign-id",
"status": "continuing",
"overview": "some interesting description of the artist",
"artistType": "Person",
"disambiguation": "American pianist",
"path": "/nfs/music/test-artist",
"members": [{"name": "alex", "instrument": "piano"}],
"qualityProfileId": 1,
"metadataProfileId": 1,
"monitored": true,
"monitorNewItems": "all",
"genres": ["soundtrack"],
"tags": [1],
"added": "2023-01-01T00:00:00Z",
"ratings": { "votes": 15, "value": 8.4 },
"statistics": {
"albumCount": 1,
"trackFileCount": 15,
"trackCount": 15,
"totalTrackCount": 15,
"sizeOnDisk": 12345,
"percentOfTracks": 99.9
}
}
}]});
let response: BlocklistResponse = serde_json::from_value(blocklist_json.clone()).unwrap();
let (mock, app, _server) = MockServarrApi::get()
.returns(blocklist_json)
.build_for(LidarrEvent::GetBlocklist)
.await;
app.lock().await.data.lidarr_data.blocklist.sort_asc = true;
app
.lock()
.await
.push_navigation_stack(ActiveLidarrBlock::BlocklistSortPrompt.into());
let cmp_fn = |a: &BlocklistItem, b: &BlocklistItem| {
a.source_title
.to_lowercase()
.cmp(&b.source_title.to_lowercase())
};
let blocklist_sort_option = SortOption {
name: "Source Title",
cmp_fn: Some(cmp_fn),
};
app
.lock()
.await
.data
.lidarr_data
.blocklist
.sorting(vec![blocklist_sort_option]);
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
let LidarrSerdeable::BlocklistResponse(blocklist) = network
.handle_lidarr_event(LidarrEvent::GetBlocklist)
.await
.unwrap()
else {
panic!("Expected BlocklistResponse")
};
mock.assert_async().await;
assert_is_empty!(app.lock().await.data.lidarr_data.blocklist);
assert!(app.lock().await.data.lidarr_data.blocklist.sort_asc);
assert_eq!(blocklist, response);
}
}
@@ -0,0 +1,92 @@
use crate::models::Route;
use crate::models::lidarr_models::{BlocklistItem, BlocklistResponse};
use crate::models::servarr_data::lidarr::lidarr_data::ActiveLidarrBlock;
use crate::network::lidarr_network::LidarrEvent;
use crate::network::{Network, RequestMethod};
use anyhow::Result;
use log::info;
use serde_json::{Value, json};
#[cfg(test)]
#[path = "lidarr_blocklist_network_tests.rs"]
mod lidarr_blocklist_network_tests;
impl Network<'_, '_> {
pub(in crate::network::lidarr_network) async fn clear_lidarr_blocklist(&mut self) -> Result<()> {
info!("Clearing Lidarr blocklist");
let event = LidarrEvent::ClearBlocklist;
let ids = self
.app
.lock()
.await
.data
.lidarr_data
.blocklist
.items
.iter()
.map(|item| item.id)
.collect::<Vec<i64>>();
let request_props = self
.request_props_from(
event,
RequestMethod::Delete,
Some(json!({"ids": ids})),
None,
None,
)
.await;
self
.handle_request::<Value, ()>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn delete_lidarr_blocklist_item(
&mut self,
blocklist_item_id: i64,
) -> Result<()> {
let event = LidarrEvent::DeleteBlocklistItem(blocklist_item_id);
info!("Deleting Lidarr blocklist item for item with id: {blocklist_item_id}");
let request_props = self
.request_props_from(
event,
RequestMethod::Delete,
None::<()>,
Some(format!("/{blocklist_item_id}")),
None,
)
.await;
self
.handle_request::<(), ()>(request_props, |_, _| ())
.await
}
pub(in crate::network::lidarr_network) async fn get_lidarr_blocklist(
&mut self,
) -> Result<BlocklistResponse> {
info!("Fetching Lidarr blocklist");
let event = LidarrEvent::GetBlocklist;
let request_props = self
.request_props_from(event, RequestMethod::Get, None::<()>, None, None)
.await;
self
.handle_request::<(), BlocklistResponse>(request_props, |blocklist_resp, mut app| {
if !matches!(
app.get_current_route(),
Route::Lidarr(ActiveLidarrBlock::BlocklistSortPrompt, _)
) {
let mut blocklist_vec: Vec<BlocklistItem> = blocklist_resp.records;
blocklist_vec.sort_by_key(|a| a.id);
app.data.lidarr_data.blocklist.set_items(blocklist_vec);
app.data.lidarr_data.blocklist.apply_sorting_toggle(false);
}
})
.await
}
}
+1 -1
View File
@@ -31,7 +31,7 @@ impl Network<'_, '_> {
Route::Lidarr(ActiveLidarrBlock::HistorySortPrompt, _)
) {
let mut history_vec = history_response.records;
history_vec.sort_by(|a, b| a.id.cmp(&b.id));
history_vec.sort_by_key(|a| a.id);
app.data.lidarr_data.history.set_items(history_vec);
app.data.lidarr_data.history.apply_sorting_toggle(false);
}
@@ -33,7 +33,7 @@ impl Network<'_, '_> {
self
.handle_request::<(), Vec<Album>>(request_props, |mut albums_vec, mut app| {
albums_vec.sort_by(|a, b| a.id.cmp(&b.id));
albums_vec.sort_by_key(|a| a.id);
app.data.lidarr_data.albums.set_items(albums_vec);
})
.await
@@ -89,7 +89,7 @@ impl Network<'_, '_> {
.get_or_insert_default();
let mut history_vec = history_items;
history_vec.sort_by(|a, b| a.id.cmp(&b.id));
history_vec.sort_by_key(|a| a.id);
album_details_modal.album_history.set_items(history_vec);
album_details_modal
.album_history
@@ -64,7 +64,7 @@ impl Network<'_, '_> {
app.get_current_route(),
Route::Lidarr(ActiveLidarrBlock::ArtistsSortPrompt, _)
) {
artists_vec.sort_by(|a, b| a.id.cmp(&b.id));
artists_vec.sort_by_key(|a| a.id);
app.data.lidarr_data.artists.set_items(artists_vec);
app.data.lidarr_data.artists.apply_sorting_toggle(false);
}
@@ -309,7 +309,7 @@ impl Network<'_, '_> {
let artist_history = &mut app.data.lidarr_data.artist_history;
if !is_sorting {
history_vec.sort_by(|a, b| a.id.cmp(&b.id));
history_vec.sort_by_key(|a| a.id);
artist_history.set_items(history_vec);
artist_history.apply_sorting_toggle(false);
}
@@ -1,8 +1,10 @@
#[cfg(test)]
mod tests {
use crate::models::lidarr_models::LidarrReleaseDownloadBody;
use crate::models::servarr_data::Notification;
use crate::network::lidarr_network::LidarrEvent;
use crate::network::network_tests::test_utils::{MockServarrApi, test_network};
use pretty_assertions::assert_eq;
use serde_json::json;
#[tokio::test]
@@ -30,5 +32,51 @@ mod tests {
mock.assert_async().await;
assert_ok!(result);
assert_eq!(
app.lock().await.notification,
Some(Notification::new(
"Download Result".to_owned(),
"Download request sent successfully".to_owned(),
true,
))
);
}
#[tokio::test]
async fn test_handle_download_lidarr_release_event_sets_failure_notification_on_error() {
let params = LidarrReleaseDownloadBody {
guid: "1234".to_owned(),
indexer_id: 2,
};
let (mock, app, _server) = MockServarrApi::post()
.with_request_body(json!({
"guid": "1234",
"indexerId": 2,
}))
.returns(json!({}))
.status(500)
.build_for(LidarrEvent::DownloadRelease(params.clone()))
.await;
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
let result = network
.handle_lidarr_event(LidarrEvent::DownloadRelease(params))
.await;
mock.assert_async().await;
assert_err!(result);
let app = app.lock().await;
assert_is_empty!(app.error.text);
assert_some_eq_x!(
&app.notification,
&Notification::new(
"Download Failed".to_owned(),
"Download request failed. Check the logs for more details.".to_owned(),
false,
)
);
}
}
+22 -3
View File
@@ -1,4 +1,5 @@
use crate::models::lidarr_models::LidarrReleaseDownloadBody;
use crate::models::servarr_data::Notification;
use crate::network::lidarr_network::LidarrEvent;
use crate::network::{Network, RequestMethod};
use anyhow::Result;
@@ -31,8 +32,26 @@ impl Network<'_, '_> {
)
.await;
self
.handle_request::<LidarrReleaseDownloadBody, Value>(request_props, |_, _| ())
.await
let result = self
.handle_request::<LidarrReleaseDownloadBody, Value>(request_props, |_, mut app| {
app.notification = Some(Notification::new(
"Download Result".to_owned(),
"Download request sent successfully".to_owned(),
true,
));
})
.await;
if result.is_err() {
let mut app = self.app.lock().await;
std::mem::take(&mut app.error.text);
app.notification = Some(Notification::new(
"Download Failed".to_owned(),
"Download request failed. Check the logs for more details.".to_owned(),
false,
));
}
result
}
}
@@ -55,7 +55,7 @@ impl Network<'_, '_> {
self
.handle_request::<(), Vec<Track>>(request_props, |mut track_vec, mut app| {
track_vec.sort_by(|a, b| a.id.cmp(&b.id));
track_vec.sort_by_key(|a| a.id);
let album_details_modal = app
.data
.lidarr_data
@@ -238,7 +238,7 @@ impl Network<'_, '_> {
.into_iter()
.filter(|it| it.track_id == track_id)
.collect();
history_vec.sort_by(|a, b| a.id.cmp(&b.id));
history_vec.sort_by_key(|a| a.id);
track_details_modal.track_history.set_items(history_vec);
track_details_modal
.track_history
@@ -3,10 +3,10 @@
pub mod test_utils {
use crate::models::lidarr_models::{
AddArtistSearchResult, Album, AlbumStatistics, Artist, ArtistStatistics, ArtistStatus,
AudioTags, DownloadRecord, DownloadStatus, DownloadsResponse, EditArtistParams,
LidarrHistoryData, LidarrHistoryEventType, LidarrHistoryItem, LidarrHistoryWrapper,
LidarrRelease, LidarrTask, LidarrTaskName, MediaInfo, Member, MetadataProfile,
NewItemMonitorType, Ratings, SystemStatus, Track, TrackFile,
AudioTags, BlocklistItem, BlocklistResponse, DownloadRecord, DownloadStatus, DownloadsResponse,
EditArtistParams, LidarrHistoryData, LidarrHistoryEventType, LidarrHistoryItem,
LidarrHistoryWrapper, LidarrRelease, LidarrTask, LidarrTaskName, MediaInfo, Member,
MetadataProfile, NewItemMonitorType, Ratings, SystemStatus, Track, TrackFile,
};
use crate::models::servarr_models::IndexerSettings;
use crate::models::servarr_models::{
@@ -477,4 +477,25 @@ pub mod test_utils {
track_file: Some(track_file()),
}
}
pub fn blocklist_item() -> BlocklistItem {
BlocklistItem {
id: 1,
artist_id: 1,
album_ids: Some(vec![1.into()]),
source_title: "Alex - Something".to_string(),
quality: quality_wrapper(),
date: DateTime::from(DateTime::parse_from_rfc3339("2023-05-20T21:29:16Z").unwrap()),
protocol: "usenet".to_string(),
indexer: "NZBgeek (Prowlarr)".to_string(),
message: "test message".to_string(),
artist: artist(),
}
}
pub fn blocklist_response() -> BlocklistResponse {
BlocklistResponse {
records: vec![blocklist_item()],
}
}
}
@@ -159,6 +159,9 @@ mod tests {
}
#[rstest]
#[case(LidarrEvent::ClearBlocklist, "/blocklist/bulk")]
#[case(LidarrEvent::DeleteBlocklistItem(0), "/blocklist")]
#[case(LidarrEvent::GetBlocklist, "/blocklist?page=1&pageSize=10000")]
#[case(LidarrEvent::GetDiskSpace, "/diskspace")]
#[case(LidarrEvent::GetMetadataProfiles, "/metadataprofile")]
#[case(LidarrEvent::GetQualityProfiles, "/qualityprofile")]
+16
View File
@@ -9,6 +9,7 @@ use crate::models::lidarr_models::{
use crate::models::servarr_models::{EditIndexerParams, IndexerSettings, QualityProfile, Tag};
use crate::network::{Network, RequestMethod};
mod blocklist;
mod downloads;
mod history;
mod indexers;
@@ -29,8 +30,10 @@ pub enum LidarrEvent {
AddArtist(AddArtistBody),
AddRootFolder(AddLidarrRootFolderBody),
AddTag(String),
ClearBlocklist,
DeleteAlbum(DeleteParams),
DeleteArtist(DeleteParams),
DeleteBlocklistItem(i64),
DeleteDownload(i64),
DeleteIndexer(i64),
DeleteRootFolder(i64),
@@ -47,6 +50,7 @@ pub enum LidarrEvent {
GetArtistHistory(i64),
GetAllIndexerSettings,
GetArtistDetails(i64),
GetBlocklist,
GetDiscographyReleases(i64),
GetDiskSpace,
GetDownloads(u64),
@@ -87,7 +91,9 @@ impl NetworkResource for LidarrEvent {
fn resource(&self) -> &'static str {
match &self {
LidarrEvent::AddTag(_) | LidarrEvent::DeleteTag(_) | LidarrEvent::GetTags => "/tag",
LidarrEvent::ClearBlocklist => "/blocklist/bulk",
LidarrEvent::DeleteTrackFile(_) | LidarrEvent::GetTrackFiles(_) => "/trackfile",
LidarrEvent::DeleteBlocklistItem(_) => "/blocklist",
LidarrEvent::GetAllIndexerSettings | LidarrEvent::EditAllIndexerSettings(_) => {
"/config/indexer"
}
@@ -104,6 +110,7 @@ impl NetworkResource for LidarrEvent {
LidarrEvent::GetArtistHistory(_)
| LidarrEvent::GetAlbumHistory(_, _)
| LidarrEvent::GetTrackHistory(_, _, _) => "/history/artist",
LidarrEvent::GetBlocklist => "/blocklist?page=1&pageSize=10000",
LidarrEvent::GetLogs(_) => "/log",
LidarrEvent::GetDiskSpace => "/diskspace",
LidarrEvent::GetDownloads(_) | LidarrEvent::DeleteDownload(_) => "/queue",
@@ -157,12 +164,20 @@ impl Network<'_, '_> {
.add_lidarr_root_folder(path)
.await
.map(LidarrSerdeable::from),
LidarrEvent::ClearBlocklist => self
.clear_lidarr_blocklist()
.await
.map(LidarrSerdeable::from),
LidarrEvent::DeleteAlbum(params) => {
self.delete_album(params).await.map(LidarrSerdeable::from)
}
LidarrEvent::DeleteArtist(params) => {
self.delete_artist(params).await.map(LidarrSerdeable::from)
}
LidarrEvent::DeleteBlocklistItem(blocklist_item_id) => self
.delete_lidarr_blocklist_item(blocklist_item_id)
.await
.map(LidarrSerdeable::from),
LidarrEvent::DeleteDownload(download_id) => self
.delete_lidarr_download(download_id)
.await
@@ -218,6 +233,7 @@ impl Network<'_, '_> {
.get_album_releases(artist_id, album_id)
.await
.map(LidarrSerdeable::from),
LidarrEvent::GetBlocklist => self.get_lidarr_blocklist().await.map(LidarrSerdeable::from),
LidarrEvent::GetDiscographyReleases(artist_id) => self
.get_artist_discography_releases(artist_id)
.await
@@ -16,21 +16,34 @@ mod tests {
async fn test_handle_get_diskspace_event() {
let diskspace_json = json!([
{
"path": "/path1",
"freeSpace": 1111,
"totalSpace": 2222,
},
{
"path": "/path2",
"freeSpace": 3333,
"totalSpace": 4444
}
]);
let response: Vec<DiskSpace> = serde_json::from_value(diskspace_json.clone()).unwrap();
let (mock, app, _server) = MockServarrApi::get()
.returns(diskspace_json)
.build_for(LidarrEvent::GetDiskSpace)
.await;
app.lock().await.server_tabs.set_index(2);
let mut network = test_network(&app);
let disk_space_vec = vec![
DiskSpace {
path: Some("/path1".to_owned()),
free_space: 1111,
total_space: 2222,
},
DiskSpace {
path: Some("/path2".to_owned()),
free_space: 3333,
total_space: 4444,
},
];
let result = network.handle_lidarr_event(LidarrEvent::GetDiskSpace).await;
@@ -40,8 +53,11 @@ mod tests {
panic!("Expected DiskSpaces");
};
assert_eq!(disk_spaces, response);
assert!(!app.lock().await.data.lidarr_data.disk_space_vec.is_empty());
assert_eq!(
app.lock().await.data.lidarr_data.disk_space_vec,
disk_space_vec
);
assert_eq!(disk_spaces, disk_space_vec);
}
#[tokio::test]
+2 -5
View File
@@ -50,7 +50,7 @@ impl Network<'_, '_> {
let log_lines = logs
.into_iter()
.map(|log| {
if log.exception.is_some() {
if let Some(exception) = log.exception {
HorizontallyScrollableText::from(format!(
"{}|{}|{}|{}|{}",
log.time,
@@ -63,10 +63,7 @@ impl Network<'_, '_> {
.exception_type
.as_ref()
.expect("exception_type must exist when exception is present"),
log
.exception
.as_ref()
.expect("exception must exist in this branch")
exception
))
} else {
HorizontallyScrollableText::from(format!(
+2 -1
View File
@@ -229,6 +229,7 @@ impl<'a, 'b> Network<'a, 'b> {
uri,
api_token,
ssl_cert_path,
ssl,
custom_headers: custom_headers_option,
..
} = app
@@ -245,7 +246,7 @@ impl<'a, 'b> Network<'a, 'b> {
let mut uri = if let Some(servarr_uri) = uri {
format!("{servarr_uri}/api/{api_version}{resource}")
} else {
let protocol = if ssl_cert_path.is_some() {
let protocol = if ssl_cert_path.is_some() || ssl.unwrap_or(false) {
"https"
} else {
"http"
+78 -1
View File
@@ -409,7 +409,7 @@ mod tests {
#[tokio::test]
#[should_panic(expected = "Servarr config is undefined")]
#[rstest]
async fn test_request_props_from_requires_radarr_config_to_be_present_for_all_network_events(
async fn test_request_props_from_requires_config_to_be_present_for_all_network_events(
#[values(RadarrEvent::HealthCheck, SonarrEvent::HealthCheck)] network_event: impl Into<NetworkEvent>
+ NetworkResource,
) {
@@ -492,6 +492,82 @@ mod tests {
assert!(request_props.custom_headers.is_empty());
}
#[rstest]
#[tokio::test]
async fn test_request_props_from_custom_config_ssl_doesnt_affect_ssl_cert_path(
#[values(RadarrEvent::GetMovies, SonarrEvent::ListSeries)] network_event: impl Into<NetworkEvent>
+ NetworkResource,
#[values(Some(true), Some(false), None)] ssl_option: Option<bool>,
) {
let api_token = "testToken1234".to_owned();
let app_arc = Arc::new(Mutex::new(App::test_default()));
let resource = network_event.resource();
let servarr_config = ServarrConfig {
host: Some("192.168.0.123".to_owned()),
port: Some(8080),
api_token: Some(api_token.clone()),
ssl_cert_path: Some("/test/cert.crt".to_owned()),
ssl: ssl_option,
..ServarrConfig::default()
};
{
let mut app = app_arc.lock().await;
app.server_tabs.tabs[0].config = Some(servarr_config.clone());
app.server_tabs.tabs[1].config = Some(servarr_config);
}
let network = test_network(&app_arc);
let request_props = network
.request_props_from(network_event, RequestMethod::Get, None::<()>, None, None)
.await;
assert_str_eq!(
request_props.uri,
format!("https://192.168.0.123:8080/api/v3{resource}")
);
assert_eq!(request_props.method, RequestMethod::Get);
assert_eq!(request_props.body, None);
assert_str_eq!(request_props.api_token, api_token);
assert!(request_props.custom_headers.is_empty());
}
#[rstest]
#[tokio::test]
async fn test_request_props_uses_ssl_property(
#[values(RadarrEvent::GetMovies, SonarrEvent::ListSeries)] network_event: impl Into<NetworkEvent>
+ NetworkResource,
) {
let api_token = "testToken1234".to_owned();
let app_arc = Arc::new(Mutex::new(App::test_default()));
let resource = network_event.resource();
let servarr_config = ServarrConfig {
host: Some("192.168.0.123".to_owned()),
port: Some(8080),
api_token: Some(api_token.clone()),
ssl: Some(true),
..ServarrConfig::default()
};
{
let mut app = app_arc.lock().await;
app.server_tabs.tabs[0].config = Some(servarr_config.clone());
app.server_tabs.tabs[1].config = Some(servarr_config);
}
let network = test_network(&app_arc);
let request_props = network
.request_props_from(network_event, RequestMethod::Get, None::<()>, None, None)
.await;
assert_str_eq!(
request_props.uri,
format!("https://192.168.0.123:8080/api/v3{resource}")
);
assert_eq!(request_props.method, RequestMethod::Get);
assert_eq!(request_props.body, None);
assert_str_eq!(request_props.api_token, api_token);
assert!(request_props.custom_headers.is_empty());
}
#[rstest]
#[tokio::test]
async fn test_request_props_from_custom_config_custom_headers(
@@ -862,6 +938,7 @@ pub(in crate::network) mod test_utils {
host,
port,
api_token: Some("test1234".to_owned()),
monitored_storage_paths: Some(vec!["/path1".to_owned()]),
..ServarrConfig::default()
};
+1 -1
View File
@@ -83,7 +83,7 @@ impl Network<'_, '_> {
Route::Radarr(ActiveRadarrBlock::BlocklistSortPrompt, _)
) {
let mut blocklist_vec = blocklist_resp.records;
blocklist_vec.sort_by(|a, b| a.id.cmp(&b.id));
blocklist_vec.sort_by_key(|a| a.id);
app.data.radarr_data.blocklist.set_items(blocklist_vec);
app.data.radarr_data.blocklist.apply_sorting_toggle(false);
}
@@ -128,7 +128,7 @@ impl Network<'_, '_> {
app.get_current_route(),
Route::Radarr(ActiveRadarrBlock::CollectionsSortPrompt, _)
) {
collections_vec.sort_by(|a, b| a.id.cmp(&b.id));
collections_vec.sort_by_key(|a| a.id);
app.data.radarr_data.collections.set_items(collections_vec);
app.data.radarr_data.collections.apply_sorting_toggle(false);
}
+1 -1
View File
@@ -31,7 +31,7 @@ impl Network<'_, '_> {
Route::Radarr(ActiveRadarrBlock::HistorySortPrompt, _)
) {
let mut history_vec = history_response.records;
history_vec.sort_by(|a, b| a.id.cmp(&b.id));
history_vec.sort_by_key(|a| a.id);
app.data.radarr_data.history.set_items(history_vec);
app.data.radarr_data.history.apply_sorting_toggle(false);
}

Some files were not shown because too many files have changed in this diff Show More