initial version, compatible with octo v.2026.11.15
arnaucube git@arnaucube.com
Sat, 28 Nov 2026 10:32:48 +0100
22 files changed,
9876 insertions(+),
0 deletions(-)
jump to
A
Cargo.lock
@@ -0,0 +1,2151 @@
+# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cassowary" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.1", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "compact_str" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossterm" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +dependencies = [ + "bitflags", + "crossterm_winapi", + "mio", + "parking_lot", + "rustix", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icy_sixel" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccc0a9c4770bc47b0a933256a496cfb8b6531f753ea9bccb19c6dff0ff7273fc" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "md5" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "octo-tui" +version = "0.1.0" +dependencies = [ + "anyhow", + "crossterm", + "image", + "md5", + "rand 0.8.8", + "ratatui", + "ratatui-image", + "reqwest", + "rustix", + "serde", + "serde_json", + "toml", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "ratatui" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" +dependencies = [ + "bitflags", + "cassowary", + "compact_str", + "crossterm", + "indoc", + "instability", + "itertools", + "lru", + "paste", + "strum", + "unicode-segmentation", + "unicode-truncate", + "unicode-width 0.2.0", +] + +[[package]] +name = "ratatui-image" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a392932bda01221984893653e1b9907d87f8db57c4528ed72f7dc4297e135e8" +dependencies = [ + "base64 0.21.7", + "icy_sixel", + "image", + "rand 0.8.8", + "ratatui", + "rustix", + "thiserror 1.0.69", + "windows", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width 0.1.14", +] + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicode-width" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" +dependencies = [ + "windows-core", + "windows-targets", +] + +[[package]] +name = "windows-core" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-result", + "windows-strings", + "windows-targets", +] + +[[package]] +name = "windows-implement" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result", + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +]
A
Cargo.toml
@@ -0,0 +1,20 @@
+[package] +name = "octo-tui" +version = "0.1.0" +edition = "2024" +license = "GPL-3.0-only" +description = "A Vim-friendly terminal player for Octo and Subsonic" + +[dependencies] +anyhow = "1" +crossterm = "0.28" +image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif"] } +ratatui-image = { version = "=4.2.0", default-features = false } +rustix = { version = "0.38", features = ["event", "stdio"] } +md5 = "0.7" +rand = "0.8" +ratatui = "0.29" +reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "0.8"
A
LICENSE
@@ -0,0 +1,675 @@
+ GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. +
A
README.md
@@ -0,0 +1,108 @@
+# Octo TUI + +Octo TUI is a Rust terminal interface for playing music from an [Octo server](https://github.com/winters27/octo). It also supports **Navidrome and Subsonic** and is based on the features and protocol implementation in [Octo Player](https://github.com/winters27/octo-player). Browse with Vim keys, stream music, build a queue, and discover songs beyond your library when connected to Octo. + +## Screenshots + + + +Vim-like shortcut mapping, available in the player by pressing `?`: + + + +## Run + +Requires Rust/Cargo and **mpv** for audio playback on Linux or macOS. Browsing works without mpv. + +```sh +# Debian / Ubuntu +sudo apt install mpv + +cargo build --release +``` + +Connect to your server using environment variables: + +```sh +export OCTO_SERVER=https://music.example.com +export OCTO_USERNAME=your-name +read -rs 'OCTO_PASSWORD?Server password: '; echo # Zsh +export OCTO_PASSWORD +cargo run --release +``` + +Alternatively copy `config.example.toml` to `~/.config/octo-tui/config.toml`. `--config PATH` selects another file. Environment variables override configuration. Servers with API-key authentication can use `OCTO_API_KEY` instead of username/password. Server addresses may include a reverse-proxy subpath, such as `https://example.com/music`. + +The config supports `server`, `username`, `password`, `api_key`, `volume` (0–100), and `theme`. Prefer environment variables for secrets; use `chmod 600` if storing credentials in a file. HTTPS is recommended: Subsonic token authentication does not encrypt the connection. Credentials and signed URLs are excluded from displayed HTTP errors and saved queues. + +## Features + +- `0 Home` opens immediately at startup, with Recently played, Recently added, Most played, Rediscover, Highest rated, History, Discover new music, and Stations. Move with `j`/`k` and press Enter to open a section. The first five sections browse server-provided album lists; open an album to browse or play its tracks. Recently played and Most played reflect history recorded by your server, not a separate local history. Use `<`/`>` for additional album pages, `R` to refresh, and Backspace to return to Home. + +- Albums with newest, alphabetical, frequent, recent and random ordering; artists, songs, genres, and playlists. Press `i` on a song to open its artist’s tracks in one flattened list, with an Album column. Albums load concurrently, up to four at a time, while retaining the server’s album and track order. Songs without an artist ID use an exact-name lookup; ambiguous or missing matches show an error. +- Press `a` on a song to choose an existing playlist with `j`/`k`, then Enter to append it. Select “Create new playlist” or press `n` to enter a name and create it with the selected song. Esc cancels or returns to the picker. All playlists are shown, matching panel `4`. Lists explicitly marked read-only by the server are labeled and cannot be modified; normal playlist updates remain subject to server permissions. Errors stay visible in the dialog. +- Song lists include a Year column when space permits, using the server’s release year (or album year when the track omits it); unknown years show “—”. +- `/` finds the first matching title, artist, or album in the current view as you type, keeping every row visible. Enter keeps the cursor position; Esc restores the original position. It searches only loaded rows. `1 Search` opens server search across songs, albums and artists; Enter submits the query. `2 Artists` opens artists. Album and song pages contain 100 entries, with explicit paging. +- Octo charts, station tracks and song radio. Standard Subsonic discovery uses random library songs and server-supported similar songs. +- Clear `DISCOVER` labels for external tracks, with `d` to request a download into your server library. +- A “Suggested by” column shows the service Octo reports (Last.fm, YouTube Music, Sounds alike, ListenBrainz, etc.). The selected song's source also appears in the footer on narrow terminals. Chart-level sources fill missing per-track sources; absent external-song sources are labeled “Unknown”. This identifies the recommendation provider, not necessarily the audio host. +- A separate “Loaded from” column and footer label distinguish playback origin from recommendation source. Library tracks show “Library”; external tracks on a confirmed Octo server show “YouTube (default)”; other unknown external providers show “Unknown”. Octo's public song API does not report the upstream actually chosen for a particular stream: the default label follows its [documented playback behavior](https://github.com/winters27/octo#playback-and-acquisition), and a ready local/acquired copy can take precedence. It is not a live provider verification. +- SIXEL album/song covers follow the currently playing track, including while paused; browsing does not change the cover. The song title and artist appear below it. Downloads and decoding run in the background with an eight-image memory cache. +- Dark, Monokai, Spotifyish, Nord, Gruvbox, Daylight and Paper themes (Spotifyish is the default); switch live with `t`. +- A live **Queue** box immediately below the cover shows the current track and upcoming songs. It follows playback and queue edits; press `8` to manage the full queue. Playing songs keep their normal text color in both queue panels. Panel `8` opens at the current song. All song-list panels mark the current song with a bold `PLAYING` or `PAUSED` status independently of your cursor; Queue marks only the active occurrence of duplicate songs. On wide terminals it remains available with `--no-art` when the queue has songs. +- **History (`9`)** appears below Queue (`8`) and remembers songs played in this TUI, newest first. It records once a track has loaded and playback advances; queued songs and failed starts are excluded. It keeps the latest 1,000 distinct tracks per server/account across restarts. Press `a` on a history entry to add it to a playlist. History is local to this player, separate from Home’s server-provided Recently played album list. +- Streaming through mpv, pause, seek, volume, automatic next track, queue repeat, shuffle, removal and reordering. +- Navidrome Now Playing notifications when library tracks start. The server can display the current track, and play counts are unaffected by the notification. +- Queue, listening history, volume and the selected theme saved separately for each server/account under `$XDG_CONFIG_HOME/octo-tui` (default `~/.config/octo-tui`). Playback starts only on request after restarting. +- Background network workers keep navigation responsive; outdated navigation responses are discarded. + + +## Library-only mode + +Press `m` to toggle **Library only**; the header shows when it is enabled. The choice is saved per server/account. Search, radio, stations, albums, artists, playlists and History hide songs Octo marks as external. Discover offers random library songs. No additional audio downloads are requested by this mode; library audio still streams from your server. + +Enabling it removes external songs from the current queue and stops playback if the current track is external. Library tracks keep playing. History is preserved, and online results become available again when you switch the mode off. A radio or station that returns only external tracks shows an empty library-only view. + +## Covers and themes + +SIXEL support is queried at startup. The cover panel appears on terminals at least 100 columns wide and 20 rows high; it hides automatically on smaller terminals. Terminals without detected SIXEL support retain the text interface. + +```sh +cargo run -- --theme monokai +cargo run -- --theme spotifyish +cargo run -- --no-art +``` + +`--no-art` disables artwork and the capability query. Inside tmux, enable `allow-passthrough` for graphics support. Missing or failed covers show a placeholder and do not interrupt playback. + +**Gruvbox** is a dark theme using the [original Gruvbox palette](https://github.com/morhetz/gruvbox): warm gray backgrounds, cream text and yellow accents. Select it with `--theme gruvbox` or `theme = "gruvbox"` in your config. + +For bright surroundings, **Daylight** uses a white background with dark text and blue accents; **Paper** uses a warm ivory background with dark text and brown accents. Both use stronger borders and high-contrast secondary text. Select them with `--theme daylight` / `--theme paper`, or press `t` to cycle. + +Set a default in your config: + +```toml +theme = "monokai" # dark, monokai, spotifyish, nord, gruvbox, daylight, paper +``` + +Theme priority at startup is `--theme`, then config `theme`, then your saved session choice, then Spotifyish. Live changes are saved per server/account. + +## Server compatibility and playback troubleshooting + +The API was checked against [Octo Player revision `1f46c3a8`](https://github.com/winters27/octo-player/commit/1f46c3a8) (2026-11-15). Its Subsonic protocol version remains `1.16.1`. Stream requests use `format=raw` and an `octoPlay` token per queue entry, preserved when replaying or reordering that entry. Tokens are regenerated when a new queue replaces the current one or the app restarts. + +Playlist browsing and the add dialog share response parsing. Empty lists, malformed replies and request failures have distinct messages. Playlist writes check `octoSkipped`, including successful responses that did not add the song, and recognize `octoConflict`. Imported read-only copies and library upkeep action/notice lists cannot be used as ordinary add targets; request lists remain available. Unknown acquisition stages remain pending and continue polling. New stream-version selection, playlist folders and acquisition keep-anyway actions are not exposed by this TUI. + +Playback uses your normal mpv configuration, including audio device settings, with terminal input and video disabled. Playback errors distinguish stream access, unsupported server responses, decoding and audio output failures when mpv supplies that information. Errors do not echo signed stream URLs. If ordinary local playback works but the TUI fails, retry with the updated binary and use its specific error to distinguish server stream access from audio output problems. + +## Development + +```sh +cargo fmt --check +cargo test +cargo clippy --all-targets -- -D warnings +``` + +Tests cover original-player response compatibility, authenticated request encoding, discovery/source parsing, cover limits and stale responses, SIXEL encoding, theme persistence, download actions, navigation, queue transitions, and rendering at different terminal sizes. The test fixture in `tests/fixtures/search3.json` comes from [Octo Player’s Subsonic module](https://github.com/winters27/octo-player/tree/1f46c3a8/subsonic). + +Uses [ratatui-image](https://docs.rs/ratatui-image/4.2.0/ratatui_image/) for SIXEL integration with the existing Ratatui version, [Ratatui](https://docs.rs/ratatui/0.29.0/ratatui/), [Reqwest](https://docs.rs/reqwest/0.12.28/reqwest/), and [mpv JSON IPC](https://mpv.io/manual/stable/#json-ipc). GPL-3.0-only; see `LICENSE` and the original [Octo Player project](https://github.com/winters27/octo-player).
A
config.example.toml
@@ -0,0 +1,9 @@
+# Copy to ~/.config/octo-tui/config.toml (or use --config PATH). +server = "https://music.example.com" +username = "your-name" +# Supply OCTO_PASSWORD in the environment; passwords need not be stored here. +# OCTO_API_KEY can be used instead on servers supporting API-key authentication. +volume = 70 + +# dark, monokai, spotifyish, nord, gruvbox, daylight, paper; press t to cycle while running. +theme = "spotifyish"
A
src/api.rs
@@ -0,0 +1,1421 @@
+use crate::{ + config::Config, + downloads::Acquisition, + model::{Item, Song, View, home_items}, + playlists::{PlaylistChoice, PlaylistTarget, parse_playlist_choices}, +}; +use anyhow::{Context, Result, bail}; +use rand::RngCore; +use reqwest::{ + Url, + blocking::{Client, RequestBuilder}, +}; +use serde_json::Value; +use std::{ + sync::atomic::{AtomicU8, Ordering}, + time::Duration, +}; + +pub struct Api { + base: Url, + username: String, + password: String, + api_key: String, + http: Client, + octo: AtomicU8, + acquisition_support: std::sync::OnceLock<bool>, +} + +impl Api { + pub fn new(config: Config) -> Result<Self> { + let base = Url::parse(&format!("{}/", config.server.trim_end_matches('/'))) + .context("Invalid server address")?; + if !matches!(base.scheme(), "http" | "https") + || !base.username().is_empty() + || base.password().is_some() + || base.query().is_some() + || base.fragment().is_some() + { + bail!("Server must be an HTTP(S) address without credentials, query or fragment"); + } + Ok(Self { + base, + octo: AtomicU8::new(0), + acquisition_support: std::sync::OnceLock::new(), + username: config.username, + password: config.password, + api_key: config.api_key, + http: Client::builder() + .timeout(Duration::from_secs(180)) + .connect_timeout(Duration::from_secs(10)) + .redirect(reqwest::redirect::Policy::none()) + .build()?, + }) + } + /// Sign every call with a fresh salt; never print signed URLs in errors. + pub fn url(&self, endpoint: &str, params: &[(&str, String)]) -> Result<Url> { + let mut url = self + .base + .join(&format!("rest/{endpoint}")) + .context("Invalid endpoint")?; + let mut query = url.query_pairs_mut(); + query.extend_pairs([("v", "1.16.1"), ("c", "octo-tui"), ("f", "json")]); + if self.api_key.is_empty() { + let mut bytes = [0u8; 16]; + rand::thread_rng().fill_bytes(&mut bytes); + let salt = bytes.iter().map(|b| format!("{b:02x}")).collect::<String>(); + let token = format!("{:x}", md5::compute(format!("{}{salt}", self.password))); + query.extend_pairs([("u", self.username.as_str()), ("t", &token), ("s", &salt)]); + } else { + query.append_pair("apiKey", &self.api_key); + } + query.extend_pairs(params.iter().map(|(k, v)| (*k, v.as_str()))); + drop(query); + Ok(url) + } + pub fn call(&self, endpoint: &str, params: &[(&str, String)]) -> Result<Value> { + Self::send_json(endpoint, self.http.get(self.url(endpoint, params)?)) + } + /// Announce a track using Subsonic's Now Playing notification. + pub fn report_now_playing(&self, id: &str) -> Result<()> { + let request = self + .http + .get(self.url( + "scrobble", + &[("id", id.into()), ("submission", "false".into())], + )?) + .timeout(Duration::from_secs(5)); + Self::send_json("scrobble", request).map(|_| ()) + } + /// Read a Subsonic reply without exposing the authenticated request URL in errors. + fn send_json(endpoint: &str, request: RequestBuilder) -> Result<Value> { + let response = request + .send() + .map_err(|_| anyhow::anyhow!("{endpoint}: connection failed or timed out"))?; + let status = response.status(); + if !status.is_success() { + bail!("{endpoint}: HTTP {status}"); + } + let body: Value = response + .json() + .map_err(|_| anyhow::anyhow!("{endpoint}: invalid JSON response"))?; + envelope(body) + } + /// Limit cover downloads independently of the slower discovery endpoints. + pub fn cover_art(&self, id: &str) -> Result<image::DynamicImage> { + use std::io::Read; + const MAX_BYTES: u64 = 8 * 1024 * 1024; + let response = self + .http + .get(self.url("getCoverArt", &[("id", id.into()), ("size", "320".into())])?) + .timeout(Duration::from_secs(15)) + .send() + .map_err(|_| anyhow::anyhow!("Cover download failed"))?; + if !response.status().is_success() { + bail!("Cover unavailable (HTTP {})", response.status()); + } + if response.content_length().is_some_and(|n| n > MAX_BYTES) { + bail!("Cover is too large"); + } + let mut bytes = Vec::new(); + response + .take(MAX_BYTES + 1) + .read_to_end(&mut bytes) + .context("Cannot read cover")?; + if bytes.len() as u64 > MAX_BYTES { + bail!("Cover is too large"); + } + crate::artwork::decode(&bytes) + } + /// Only poll acquisition status on servers that advertise Octo's extension. + pub fn acquisitions(&self) -> Result<Option<Vec<Acquisition>>> { + let supported = if let Some(supported) = self.acquisition_support.get() { + *supported + } else { + let response = self.call("getOpenSubsonicExtensions", &[])?; + let supported = array(&response["openSubsonicExtensions"]) + .iter() + .any(|e| e["name"] == "octoAcquisitions"); + let _ = self.acquisition_support.set(supported); + supported + }; + if !supported { + return Ok(None); + } + let response = self.call("getAcquisitions", &[])?; + let acquisitions = array(&response["acquisitions"]["acquisition"]) + .iter() + .map(|v| serde_json::from_value(v.clone())) + .collect::<std::result::Result<Vec<Acquisition>, _>>() + .context("Invalid acquisition data")?; + Ok(Some(acquisitions)) + } + /// A completed transfer is only local once the server can return a non-external song. + pub fn library_song(&self, id: &str) -> Result<Option<Song>> { + let response = self.call("getSong", &[("id", id.into())])?; + let mut song: Song = + serde_json::from_value(response["song"].clone()).context("Invalid library song")?; + if song.is_external || song.id.is_empty() { + return Ok(None); + } + song.playback_source = None; + Ok(Some(song)) + } + /// List the same playlists as browsing, retaining explicit editability markers for the UI. + pub fn playlist_choices(&self) -> Result<Vec<PlaylistChoice>> { + let response = self.call("getPlaylists", &[])?; + let mut choices = parse_playlist_choices(playlist_rows(&response)?); + choices.sort_by_key(|p| p.name.to_lowercase()); + Ok(choices) + } + /// Fetch up to four albums at once, keeping server album order and per-track metadata. + fn artist_songs(&self, id: &str) -> Result<Vec<Item>> { + let response = self.call("getArtist", &[("id", id.into())])?; + let artist = &response["artist"]; + let load_album = |album: &Value| -> Result<Vec<Item>> { + let album_id = album["id"] + .as_str() + .filter(|id| !id.is_empty()) + .context("Artist album is missing its ID")?; + let mut songs = self.load(&View::Album(album_id.into()))?; + for item in &mut songs { + if let Item::Song(song) = item { + if song.year.is_none_or(|year| year == 0) { + song.year = release_year(&album["year"]); + } + if song.album.is_empty() { + song.album = album["name"].as_str().unwrap_or_default().into(); + } + if song.album_id.as_deref().is_none_or(str::is_empty) { + song.album_id = Some(album_id.into()); + } + if song.artist.is_empty() { + song.artist = artist["name"].as_str().unwrap_or_default().into(); + song.artist_id = Some(id.into()); + } + } + } + Ok(songs) + }; + let mut tracks = Vec::new(); + for albums in array(&artist["album"]).chunks(4) { + let batch = + std::thread::scope(|scope| -> Result<Vec<Item>> { + let pending: Vec<_> = albums + .iter() + .map(|album| scope.spawn(|| load_album(album))) + .collect(); + let mut songs = Vec::new(); + for worker in pending { + songs.extend(worker.join().map_err(|_| { + anyhow::anyhow!("Artist album loading worker failed") + })??); + } + Ok(songs) + })?; + tracks.extend(batch); + } + Ok(tracks) + } + + /// Append without replacing existing entries, or create a playlist with its first song atomically. + pub fn add_to_playlist(&self, target: &PlaylistTarget, song_id: &str) -> Result<()> { + let response = match target { + PlaylistTarget::Existing { id, .. } => self.call( + "updatePlaylist", + &[("playlistId", id.clone()), ("songIdToAdd", song_id.into())], + )?, + PlaylistTarget::New { name } => self.call( + "createPlaylist", + &[("name", name.clone()), ("songId", song_id.into())], + )?, + }; + if let Some(skipped) = response.get("octoSkipped").filter(|v| !v.is_null()) { + let skipped = skipped + .as_array() + .context("Invalid playlist skipped-song response")?; + if !skipped.is_empty() { + if matches!(target, PlaylistTarget::New { .. }) { + bail!( + "Playlist created, but the server skipped the song. Check the playlist before retrying." + ); + } + bail!("The server skipped this song; it was not added to the playlist."); + } + } + + Ok(()) + } + fn remember_extensions(&self, response: &Value) { + let octo = array(&response["openSubsonicExtensions"]).iter().any(|e| { + e["name"] + .as_str() + .is_some_and(|name| name.starts_with("octo")) + }); + self.octo.store(if octo { 2 } else { 1 }, Ordering::Relaxed); + } + /// Only Octo has the documented YouTube default; other Subsonic servers stay unknown. + fn mark_playback_sources(&self, body: &Value, items: &mut [Item]) { + if !items + .iter() + .any(|item| matches!(item,Item::Song(s) if s.is_external)) + { + return; + } + if body["type"] == "octo" { + self.octo.store(2, Ordering::Relaxed); + } + if self.octo.load(Ordering::Relaxed) == 0 + && let Ok(v) = self.call("getOpenSubsonicExtensions", &[]) + { + self.remember_extensions(&v); + } + apply_playback_source(items, self.octo.load(Ordering::Relaxed) == 2); + } + pub fn session_key(&self) -> String { + format!( + "{:x}", + md5::compute(format!("{}|{}|{}", self.base, self.username, self.api_key)) + ) + } + /// Match the original client's collection endpoints and preserve server ordering. + /// Use library-backed discovery; ownership filtering happens after local-copy resolution. + pub fn load_with_mode(&self, view: &View, library_only: bool) -> Result<Vec<Item>> { + if library_only && matches!(view, View::Discover) { + let response = self.call("getRandomSongs", &[("size", "100".into())])?; + parse_items(&response["randomSongs"]["song"], "song") + } else { + self.load(view) + } + } + + pub fn load(&self, view: &View) -> Result<Vec<Item>> { + let count = || ("count", "100".into()); + let (endpoint, params, path, kind): (&str, Vec<(&str, String)>, &[&str], &str) = match view + { + View::Albums { kind, offset } => ( + "getAlbumList2", + vec![ + ("type", kind.clone()), + ("size", "100".into()), + ("offset", offset.to_string()), + ], + &["albumList2", "album"], + "album", + ), + View::Artists => ("getArtists", vec![], &["artists", "index"], "index"), + View::Songs { offset } => ( + "search3", + vec![ + ("query", "".into()), + ("songCount", "100".into()), + ("songOffset", offset.to_string()), + ("artistCount", "0".into()), + ("albumCount", "0".into()), + ], + &["searchResult3", "song"], + "song", + ), + + View::Playlists => { + return Ok(self + .playlist_choices()? + .into_iter() + .map(|p| Item::Playlist { + id: p.id, + name: p.name, + }) + .collect()); + } + View::Genres => ("getGenres", vec![], &["genres", "genre"], "genre"), + View::Stations => ( + "getInternetRadioStations", + vec![], + &["internetRadioStations", "internetRadioStation"], + "station", + ), + View::Discover => { + let ext = self.call("getOpenSubsonicExtensions", &[]); + if let Ok(v) = &ext { + self.remember_extensions(v); + } + let charts = ext.as_ref().ok().is_some_and(|v| { + array(&v["openSubsonicExtensions"]) + .iter() + .any(|e| e["name"] == "octoTopSongs") + }); + if charts { + ( + "getTopChart", + vec![count()], + &["topSongs", "entry"], + "chart", + ) + } else { + ( + "getRandomSongs", + vec![("size", "100".into())], + &["randomSongs", "song"], + "song", + ) + } + } + View::Album(id) => ( + "getAlbum", + vec![("id", id.clone())], + &["album", "song"], + "song", + ), + View::ArtistByName(name) => { + let response = self.call( + "search3", + &[ + ("query", name.clone()), + ("artistCount", "100".into()), + ("albumCount", "0".into()), + ("songCount", "0".into()), + ], + )?; + let matches: Vec<_> = array(&response["searchResult3"]["artist"]) + .iter() + .filter(|artist| { + artist["name"].as_str().is_some_and(|candidate| { + candidate.trim().eq_ignore_ascii_case(name.trim()) + }) + }) + .filter_map(|artist| artist["id"].as_str().filter(|id| !id.trim().is_empty())) + .collect(); + return match matches.as_slice() { + [id] => self.load(&View::Artist((*id).into())), + [] => bail!("No matching artist was returned. Use / to search for the artist."), + _ => bail!("Several artists share this name. Use / to choose the artist."), + }; + } + View::Artist(id) => return self.artist_songs(id), + View::Playlist(id) => ( + "getPlaylist", + vec![("id", id.clone())], + &["playlist", "entry"], + "song", + ), + View::Genre(g) => ( + "getSongsByGenre", + vec![("genre", g.clone()), count()], + &["songsByGenre", "song"], + "song", + ), + View::Radio(id) => ( + "getSimilarSongs2", + vec![("id", id.clone()), count()], + &["similarSongs2", "song"], + "song", + ), + View::Station(id) => ( + "getStationSongs", + vec![("id", id.clone()), count()], + &["stationSongs", "entry"], + "song", + ), + View::Search(q) => { + let v = self.call( + "search3", + &[ + ("query", q.clone()), + ("songCount", "100".into()), + ("albumCount", "30".into()), + ("artistCount", "30".into()), + ], + )?; + let result = &v["searchResult3"]; + let mut items = parse_items(&result["song"], "song")?; + items.extend(parse_items(&result["album"], "album")?); + items.extend(parse_items(&result["artist"], "artist")?); + self.mark_playback_sources(&v, &mut items); + return Ok(items); + } + View::History => return Ok(vec![]), + View::Home => return Ok(home_items()), + View::Queue => return Ok(vec![]), + }; + let body = self.call(endpoint, ¶ms)?; + let value = path.iter().fold(&body, |v, key| &v[*key]); + if kind == "index" { + let mut items = vec![]; + for index in array(value) { + items.extend(parse_items(&index["artist"], "artist")?); + } + Ok(items) + } else { + let mut items = parse_items(value, kind)?; + if matches!(view, View::Album(_)) { + for item in &mut items { + if let Item::Song(song) = item + && song.year.is_none_or(|year| year == 0) + { + song.year = release_year(&body["album"]["year"]); + } + } + } + if kind == "chart" { + apply_chart_source(&mut items, body["topSongs"]["source"].as_str()); + } + self.mark_playback_sources(&body, &mut items); + Ok(items) + } + } +} + +/// Octo proxies external previews through YouTube by default, but can serve a ready local copy. +/// The wire API has no chosen-upstream field, so this label must stay explicitly provisional. +fn apply_playback_source(items: &mut [Item], octo: bool) { + if !octo { + return; + } + for item in items { + if let Item::Song(song) = item + && song.is_external + && song.playback_source.is_none() + { + song.playback_source = Some("YouTube (default)".into()); + } + } +} + +/// A chart-level provider fills only missing per-song provenance. +fn apply_chart_source(items: &mut [Item], source: Option<&str>) { + let Some(source) = source.filter(|s| !s.trim().is_empty()) else { + return; + }; + let source = match source { + "lastfm" => "Last.fm", + "deezer" => "Deezer", + "apple" => "Apple Music", + other => other, + }; + for item in items { + if let Item::Song(song) = item + && song + .octo_suggested_by + .as_deref() + .is_none_or(|s| s.trim().is_empty()) + { + song.octo_suggested_by = Some(source.into()); + } + } +} + +/// Missing lists are valid empty replies; a present list with the wrong shape is a protocol error. +fn playlist_rows(response: &Value) -> Result<&Value> { + if let Some(container) = response.get("playlists").filter(|v| !v.is_null()) { + if !container.is_object() { + bail!( + "getPlaylists: expected a playlists object, but the server returned another response shape" + ); + } + if let Some(rows) = container.get("playlist").filter(|v| !v.is_null()) + && !rows.is_array() + { + bail!( + "getPlaylists: expected a playlist array, but the server returned another response shape" + ); + } + } + Ok(&response["playlists"]["playlist"]) +} +/// Zero or absent release years mean the server has no date for this release. +fn release_year(value: &Value) -> Option<u32> { + value + .as_u64() + .and_then(|year| u32::try_from(year).ok()) + .filter(|year| *year > 0) +} +fn array(v: &Value) -> &[Value] { + v.as_array().map(Vec::as_slice).unwrap_or(&[]) +} + +/// Only expose error codes: server messages may echo signed request URLs. +fn envelope(body: Value) -> Result<Value> { + let response = body + .get("subsonic-response") + .context("Not a Subsonic JSON response")?; + if response["status"] != "ok" { + if response["error"]["octoConflict"].as_bool() == Some(true) { + bail!("The playlist changed on the server. Refresh it before retrying."); + } + bail!( + "Server rejected request (code {}). Check credentials and endpoint support.", + response["error"]["code"].as_u64().unwrap_or(0) + ); + } + Ok(response.clone()) +} +fn parse_items(value: &Value, kind: &str) -> Result<Vec<Item>> { + if kind == "playlist" { + return Ok(parse_playlist_choices(value) + .into_iter() + .map(|p| Item::Playlist { + id: p.id, + name: p.name, + }) + .collect()); + } + array(value) + .iter() + .filter(|v| kind != "chart" || v["song"].is_object()) + .map(|v| { + let text = |key: &str| v[key].as_str().unwrap_or_default().to_owned(); + Ok(match kind { + "album" => Item::Album { + id: text("id"), + name: text("name"), + artist: text("artist"), + cover_art: v["coverArt"].as_str().map(str::to_owned), + }, + "artist" => Item::Artist { + id: text("id"), + name: text("name"), + }, + "station" => Item::Station { + id: text("id"), + name: text("name"), + }, + "genre" => Item::Genre(text("value")), + "chart" => { + return if v["song"].is_object() { + Ok(Item::Song( + serde_json::from_value(v["song"].clone()) + .context("Invalid chart song")?, + )) + } else { + bail!("Chart entry has no playable song") + }; + } + _ => Item::Song( + serde_json::from_value::<Song>(v.clone()).context("Invalid song data")?, + ), + }) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn now_playing_sends_an_authenticated_notification() { + use std::{ + io::{BufRead, BufReader, Write}, + net::TcpListener, + }; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut request = String::new(); + let mut reader = BufReader::new(&mut stream); + reader.read_line(&mut request).unwrap(); + let mut parts = request.split_whitespace(); + assert_eq!(parts.next(), Some("GET")); + let url = Url::parse(&format!("http://{address}{}", parts.next().unwrap())).unwrap(); + assert_eq!(url.path(), "/music/rest/scrobble"); + let params = url + .query_pairs() + .collect::<std::collections::HashMap<_, _>>(); + assert_eq!(params["id"], "track + 42"); + assert_eq!(params["submission"], "false"); + assert_eq!(params["c"], "octo-tui"); + assert_eq!(params["apiKey"], "test-key"); + loop { + request.clear(); + if reader.read_line(&mut request).unwrap() == 0 || request == "\r\n" { + break; + } + } + let body = r#"{"subsonic-response":{"status":"ok"}}"#; + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ) + .unwrap(); + }); + let api = Api::new(Config { + server: format!("http://{address}/music"), + api_key: "test-key".into(), + ..Default::default() + }) + .unwrap(); + api.report_now_playing("track + 42").unwrap(); + server.join().unwrap(); + } + #[test] + fn playlist_errors_distinguish_empty_malformed_and_conflicting_responses() { + for response in [ + serde_json::json!({}), + serde_json::json!({"playlists":null}), + serde_json::json!({"playlists":{"playlist":[]}}), + ] { + assert!(parse_playlist_choices(playlist_rows(&response).unwrap()).is_empty()); + } + for response in [ + serde_json::json!({"playlists":[]}), + serde_json::json!({"playlists":{"playlist":{}}}), + ] { + assert!(playlist_rows(&response).is_err()); + } + let error = envelope(serde_json::json!({"subsonic-response":{"status":"failed","error":{"octoConflict":true,"message":"private"}}})).unwrap_err().to_string(); + assert!(error.contains("playlist changed")); + assert!(!error.contains("private")); + } + + #[test] + fn successful_http_replies_with_skipped_songs_do_not_report_playlist_success() { + use std::{ + io::{Read, Write}, + net::TcpListener, + }; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + for _ in 0..2 { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + stream.read_exact(&mut byte).unwrap(); + request.push(byte[0]); + } + let body = r#"{"subsonic-response":{"status":"ok","octoSkipped":["song"]}}"#; + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ) + .unwrap(); + } + }); + let api = Api::new(Config { + server: format!("http://{address}"), + ..Default::default() + }) + .unwrap(); + let existing = api + .add_to_playlist( + &PlaylistTarget::Existing { + id: "list".into(), + name: "List".into(), + }, + "song", + ) + .unwrap_err() + .to_string(); + assert!(existing.contains("not added")); + let new = api + .add_to_playlist(&PlaylistTarget::New { name: "New".into() }, "song") + .unwrap_err() + .to_string(); + assert!(new.contains("Playlist created")); + server.join().unwrap(); + } + + #[test] + fn artist_albums_load_concurrently_in_order_and_fail_without_partial_results() { + use serde_json::json; + use std::{ + io::{BufRead, BufReader, Write}, + net::{TcpListener, TcpStream}, + time::Instant, + }; + + fn request(listener: &TcpListener) -> (TcpStream, Url) { + let deadline = Instant::now() + Duration::from_secs(3); + let (stream, _) = loop { + match listener.accept() { + Ok(connection) => break connection, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + assert!( + Instant::now() < deadline, + "Album requests did not arrive concurrently" + ); + std::thread::sleep(Duration::from_millis(5)); + } + Err(error) => panic!("Accept failed: {error}"), + } + }; + stream + .set_read_timeout(Some(Duration::from_secs(3))) + .unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut first = String::new(); + reader.read_line(&mut first).unwrap(); + let url = Url::parse(&format!( + "http://localhost{}", + first.split_whitespace().nth(1).unwrap() + )) + .unwrap(); + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + } + (stream, url) + } + fn respond(mut stream: TcpStream, mut payload: Value) { + if payload.get("status").is_none() { + payload["status"] = json!("ok"); + } + let body = json!({"subsonic-response":payload}).to_string(); + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ) + .unwrap(); + } + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + for fail in [false, true] { + let (stream, url) = request(&listener); + assert_eq!(url.path(), "/rest/getArtist"); + let albums: Vec<_> = (0..9) + .map(|i| json!({"id":i.to_string(),"name":format!("Album {i}")})) + .collect(); + respond(stream, json!({"artist":{"name":"Artist","album":albums}})); + for start in [0, 4, 8] { + let count = (9 - start).min(4); + // Hold every response until the whole batch is in flight. + let mut pending = Vec::new(); + for _ in 0..count { + let (stream, url) = request(&listener); + assert_eq!(url.path(), "/rest/getAlbum"); + let index: usize = url + .query_pairs() + .find(|(k, _)| k == "id") + .unwrap() + .1 + .parse() + .unwrap(); + assert!((start..start + count).contains(&index)); + pending.push((index, stream)); + } + pending.sort_by_key(|(index, _)| *index); + for (index, stream) in pending.into_iter().rev() { + let payload = if fail && index == 8 { + json!({"status":"failed","error":{"code":70}}) + } else if index == 8 { + json!({"album":{"song":[]}}) + } else { + json!({"album":{"song":[{"id":format!("{index}-a")},{"id":format!("{index}-b")}]}}) + }; + respond(stream, payload); + } + } + } + }); + let api = Api::new(Config { + server: format!("http://{address}"), + ..Default::default() + }) + .unwrap(); + let tracks = api.load(&View::Artist("artist".into())).unwrap(); + let songs: Vec<_> = tracks + .iter() + .map(|item| match item { + Item::Song(song) => song, + _ => panic!("Expected song"), + }) + .collect(); + let expected: Vec<_> = (0..8) + .flat_map(|i| [format!("{i}-a"), format!("{i}-b")]) + .collect(); + assert_eq!( + songs.iter().map(|s| s.id.clone()).collect::<Vec<_>>(), + expected + ); + for (i, song) in songs.iter().enumerate() { + assert_eq!(song.album, format!("Album {}", i / 2)); + } + assert!(api.load(&View::Artist("artist".into())).is_err()); + server.join().unwrap(); + } + + #[test] + fn artist_name_lookup_opens_exact_artist_and_rejects_ambiguous_or_missing_matches() { + use serde_json::json; + use std::{ + io::{BufRead, BufReader, Write}, + net::TcpListener, + }; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + for (endpoint, mut payload) in [ + ( + "search3", + json!({"searchResult3":{"artist":[{"id":"wrong","name":"Artist Tribute"},{"id":"right","name":"ARTIST"}]}}), + ), + ( + "getArtist", + json!({"artist":{"name":"Artist","album":[{"id":"album","name":"Record","year":1999},{"id":"second","name":"Second","year":2005},{"id":"empty","name":"Empty"}]}}), + ), + ( + "getAlbum", + json!({"album":{"year":2020,"song":[{"id":"first","title":"First","year":null},{"id":"second-track","title":"Next","album":"Explicit album","artist":"Guest","artistId":"guest","year":2001}]}}), + ), + ( + "getAlbum", + json!({"album":{"song":[{"id":"last","title":"Last","year":0}]}}), + ), + ("getAlbum", json!({"album":{"song":[]}})), + ( + "search3", + json!({"searchResult3":{"artist":[{"id":"a","name":"Artist"},{"id":"b","name":"Artist"}]}}), + ), + ( + "search3", + json!({"searchResult3":{"artist":[{"id":"wrong","name":"Artist Tribute"}]}}), + ), + ] { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut first = String::new(); + reader.read_line(&mut first).unwrap(); + let url = Url::parse(&format!( + "http://localhost{}", + first.split_whitespace().nth(1).unwrap() + )) + .unwrap(); + assert_eq!(url.path(), format!("/rest/{endpoint}")); + if endpoint == "getArtist" { + assert!(url.query_pairs().any(|(k, v)| k == "id" && v == "right")); + } else if endpoint == "getAlbum" { + let album = url + .query_pairs() + .find(|(k, _)| k == "id") + .unwrap() + .1 + .into_owned(); + payload = match album.as_str() { + "album" => { + serde_json::json!({"album":{"year":2020,"song":[{"id":"first","title":"First","year":null},{"id":"second-track","title":"Next","album":"Explicit album","artist":"Guest","artistId":"guest","year":2001}]}}) + } + "second" => { + serde_json::json!({"album":{"song":[{"id":"last","title":"Last","year":0}]}}) + } + "empty" => serde_json::json!({"album":{"song":[]}}), + _ => panic!("Unexpected album request"), + }; + } else { + assert!( + url.query_pairs() + .any(|(k, v)| k == "query" && v == "Artist") + ); + assert!(url.query_pairs().any(|(k, v)| k == "songCount" && v == "0")); + } + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + } + let mut payload = payload; + payload["status"] = json!("ok"); + let body = json!({"subsonic-response":payload}).to_string(); + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ) + .unwrap(); + } + }); + let api = Api::new(Config { + server: format!("http://{address}"), + ..Default::default() + }) + .unwrap(); + let view = View::ArtistByName("Artist".into()); + let tracks = api.load(&view).unwrap(); + let songs: Vec<_> = tracks + .iter() + .map(|item| match item { + Item::Song(song) => song, + _ => panic!("expected flattened songs"), + }) + .collect(); + assert_eq!( + songs + .iter() + .map(|song| song.id.as_str()) + .collect::<Vec<_>>(), + ["first", "second-track", "last"] + ); + assert_eq!(songs[0].year, Some(2020)); + assert_eq!(songs[1].year, Some(2001)); + assert_eq!(songs[2].year, Some(2005)); + assert_eq!(songs[0].album, "Record"); + assert_eq!(songs[0].album_id.as_deref(), Some("album")); + assert_eq!(songs[0].artist, "Artist"); + assert_eq!(songs[1].album, "Explicit album"); + assert_eq!(songs[1].artist, "Guest"); + assert_eq!(songs[1].artist_id.as_deref(), Some("guest")); + assert_eq!(songs[2].album, "Second"); + assert!( + api.load(&view) + .unwrap_err() + .to_string() + .contains("Several artists") + ); + assert!( + api.load(&view) + .unwrap_err() + .to_string() + .contains("No matching artist") + ); + server.join().unwrap(); + } + + #[test] + fn library_discovery_requests_random_library_songs_without_online_charts() { + use std::{ + io::{BufRead, BufReader, Write}, + net::TcpListener, + }; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(3))) + .unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut first = String::new(); + reader.read_line(&mut first).unwrap(); + let url = Url::parse(&format!( + "http://localhost{}", + first.split_whitespace().nth(1).unwrap() + )) + .unwrap(); + assert_eq!(url.path(), "/rest/getRandomSongs"); + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + } + let body = r#"{"subsonic-response":{"status":"ok","randomSongs":{"song":[{"id":"local","title":"Library song"}]}}}"#; + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ) + .unwrap(); + }); + let api = Api::new(Config { + server: format!("http://{address}"), + ..Default::default() + }) + .unwrap(); + let items = api.load_with_mode(&View::Discover, true).unwrap(); + assert!(matches!(&items[..],[Item::Song(song)] if song.id == "local" && !song.is_external)); + server.join().unwrap(); + } + + #[test] + fn original_player_fixture_parses() { + let v = + envelope(serde_json::from_str(include_str!("../tests/fixtures/search3.json")).unwrap()) + .unwrap(); + let items = parse_items(&v["searchResult3"]["song"], "song").unwrap(); + assert_eq!(items.len(), 2); + assert_eq!(items[0].title(), "Nightcall"); + } + #[test] + fn charts_keep_playable_external_and_library_songs() { + let entries = serde_json::json!([ + {"rank":1,"song":{"id":"local","title":"Owned"}}, + {"rank":2,"song":{"id":"online","title":"Found","isExternal":true}}, + {"rank":3,"song":null} + ]); + let items = parse_items(&entries, "chart").unwrap(); + assert_eq!(items.len(), 2); + assert_eq!(items[0].label(), "LIBRARY"); + assert_eq!(items[1].label(), "DISCOVER"); + } + #[test] + fn provenance_preserves_individual_source_and_uses_chart_fallback() { + let mut items = parse_items( + &serde_json::json!([ + {"id":"radio","isExternal":true,"octoSuggestedBy":"Sounds alike"}, + {"id":"chart","isExternal":true}, + {"id":"unknown","isExternal":true} + ]), + "song", + ) + .unwrap(); + assert_eq!(items[2].recommendation_source(), "Unknown"); + apply_chart_source(&mut items, Some("lastfm")); + assert_eq!(items[0].recommendation_source(), "Sounds alike"); + assert_eq!(items[1].recommendation_source(), "Last.fm"); + let roundtrip: Song = serde_json::from_value( + serde_json::to_value(match &items[0] { + Item::Song(s) => s, + _ => unreachable!(), + }) + .unwrap(), + ) + .unwrap(); + assert_eq!(roundtrip.octo_suggested_by.as_deref(), Some("Sounds alike")); + } + #[test] + fn playback_source_never_uses_recommendation_provider() { + let mut items = parse_items( + &serde_json::json!([ + {"id":"local","octoSuggestedBy":"Sounds alike"}, + {"id":"outside","isExternal":true,"octoSuggestedBy":"Last.fm"} + ]), + "song", + ) + .unwrap(); + assert_eq!(items[0].playback_source(), "Library"); + assert_eq!(items[1].playback_source(), "Unknown"); + apply_playback_source(&mut items, true); + assert_eq!(items[1].playback_source(), "YouTube (default)"); + assert_eq!(items[1].recommendation_source(), "Last.fm"); + } + #[test] + fn home_history_shelves_request_server_album_order_and_page() { + use std::{ + io::{BufRead, BufReader, Write}, + net::TcpListener, + }; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + for kind in ["recent", "newest", "frequent", "random", "highest"] { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut first = String::new(); + reader.read_line(&mut first).unwrap(); + let target = first.split_whitespace().nth(1).unwrap(); + let url = Url::parse(&format!("http://localhost{target}")).unwrap(); + let params: std::collections::HashMap<_, _> = url.query_pairs().collect(); + assert_eq!(url.path(), "/rest/getAlbumList2"); + assert_eq!(params["type"], kind); + assert_eq!(params["size"], "100"); + assert_eq!(params["offset"], "100"); + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + } + let body=serde_json::json!({"subsonic-response":{"status":"ok","albumList2":{"album":[{"id":kind,"name":format!("{kind} album"),"artist":"Test artist"}]}}}).to_string(); + write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",body.len(),body).unwrap(); + } + }); + let api = Api::new(Config { + server: format!("http://{address}"), + api_key: "test-key".into(), + ..Default::default() + }) + .unwrap(); + for section in crate::model::HomeSection::ALL.into_iter().take(5) { + let mut view = section.view(); + let View::Albums { offset, kind } = &mut view else { + unreachable!() + }; + *offset = 100; + let title = format!("{kind} album"); + let items = api.load(&view).unwrap(); + assert_eq!(items[0].title(), title); + } + server.join().unwrap(); + } + #[test] + fn acquisition_poll_checks_extension_once_and_parses_server_progress() { + use std::{ + io::{BufRead, BufReader, Write}, + net::TcpListener, + }; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + for endpoint in [ + "getOpenSubsonicExtensions", + "getAcquisitions", + "getAcquisitions", + ] { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut first = String::new(); + reader.read_line(&mut first).unwrap(); + assert!(first.starts_with(&format!("GET /rest/{endpoint}?"))); + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + } + let body = if endpoint == "getOpenSubsonicExtensions" { + r#"{"subsonic-response":{"status":"ok","openSubsonicExtensions":[{"name":"octoAcquisitions","versions":[1]}]}}"# + } else { + include_str!("../tests/fixtures/acquisitions.json") + }; + write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",body.len(),body).unwrap(); + } + }); + let api = Api::new(Config { + server: format!("http://{address}"), + api_key: "test-key".into(), + ..Default::default() + }) + .unwrap(); + for _ in 0..2 { + let rows = api.acquisitions().unwrap().unwrap(); + assert_eq!(rows[0].state, "downloading"); + assert_eq!(rows[0].progress, Some(0.42)); + assert_eq!(rows[0].source.as_deref(), Some("Soulseek")); + } + server.join().unwrap(); + } + #[test] + fn playlist_browse_and_picker_parse_the_same_server_rows() { + let rows = serde_json::json!([ + {"id":7,"name":"My playlist","readonly":null}, + {"id":"station","name":"Station","readonly":true}, + {"id":"other","name":"Other playlist","readonly":"false"} + ]); + let choices = parse_playlist_choices(&rows); + let browse = parse_items(&rows, "playlist").unwrap(); + assert_eq!(choices.len(), 3); + assert_eq!(browse.len(), choices.len()); + for (choice, item) in choices.iter().zip(&browse) { + assert_eq!(choice.name, item.title()); + assert!(matches!(item,Item::Playlist {id,..} if id==&choice.id)); + } + assert!(!choices[0].readonly); + } + #[test] + fn playlist_picker_keeps_readonly_visible_and_writes_only_the_selected_song() { + use std::{ + io::{BufRead, BufReader, Write}, + net::TcpListener, + }; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + for endpoint in ["getPlaylists", "updatePlaylist", "createPlaylist"] { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut first = String::new(); + reader.read_line(&mut first).unwrap(); + let target = first.split_whitespace().nth(1).unwrap(); + let url = Url::parse(&format!("http://localhost{target}")).unwrap(); + assert_eq!(url.path(), format!("/rest/{endpoint}")); + let params: std::collections::HashMap<_, _> = url.query_pairs().collect(); + if endpoint == "updatePlaylist" { + assert_eq!(params["playlistId"], "editable"); + assert_eq!(params["songIdToAdd"], "song & 1"); + assert!(!params.contains_key("songId")); + } + if endpoint == "createPlaylist" { + assert_eq!(params["name"], "Café & music"); + assert_eq!(params["songId"], "song & 1"); + assert!(!params.contains_key("playlistId")); + } + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + } + let body = if endpoint == "getPlaylists" { + r#"{"subsonic-response":{"status":"ok","playlists":{"playlist":[{"id":"station","name":"Station","readonly":true},{"id":"editable","name":"Evening","readonly":null},{"id":"first","name":"Afternoon"}]}}}"# + } else { + r#"{"subsonic-response":{"status":"ok"}}"# + }; + write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",body.len(),body).unwrap(); + } + }); + let api = Api::new(Config { + server: format!("http://{address}"), + api_key: "test-key".into(), + ..Default::default() + }) + .unwrap(); + let choices = api.playlist_choices().unwrap(); + assert_eq!(choices.len(), 3); + assert_eq!(choices[0].name, "Afternoon"); + assert!(choices[2].readonly); + api.add_to_playlist( + &PlaylistTarget::Existing { + id: "editable".into(), + name: "Evening".into(), + }, + "song & 1", + ) + .unwrap(); + api.add_to_playlist( + &PlaylistTarget::New { + name: "Café & music".into(), + }, + "song & 1", + ) + .unwrap(); + server.join().unwrap(); + } + #[test] + fn library_lookup_confirms_indexed_metadata_before_switching_ids() { + use std::{ + io::{BufRead, BufReader, Write}, + net::TcpListener, + }; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + for (id, external) in [("indexed", false), ("waiting", true)] { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut first = String::new(); + reader.read_line(&mut first).unwrap(); + let url = Url::parse(&format!( + "http://localhost{}", + first.split_whitespace().nth(1).unwrap() + )) + .unwrap(); + assert_eq!(url.path(), "/rest/getSong"); + assert!(url.query_pairs().any(|(k, v)| k == "id" && v == id)); + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + } + let body=serde_json::json!({"subsonic-response":{"status":"ok","song":{"id":id,"title":"Track","isExternal":external,"playbackSource":"YouTube (default)"}}}).to_string(); + write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",body.len(),body).unwrap(); + } + }); + let api = Api::new(Config { + server: format!("http://{address}"), + api_key: "test-key".into(), + ..Default::default() + }) + .unwrap(); + let song = api.library_song("indexed").unwrap().unwrap(); + assert_eq!(song.id, "indexed"); + assert!(!song.is_external); + assert!(song.playback_source.is_none()); + assert!(api.library_song("waiting").unwrap().is_none()); + server.join().unwrap(); + } + #[test] + fn discovery_uses_octos_nested_chart_response() { + use std::{ + io::{BufRead, BufReader, Write}, + net::TcpListener, + }; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + for endpoint in ["getOpenSubsonicExtensions", "getTopChart"] { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut request = String::new(); + reader.read_line(&mut request).unwrap(); + assert!(request.starts_with(&format!("GET /music/rest/{endpoint}?"))); + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + } + let body = if endpoint == "getTopChart" { + r#"{"subsonic-response":{"status":"ok","topSongs":{"source":"lastfm","entry":[{"song":{"id":"found","title":"New music","isExternal":true}}]}}}"# + } else { + r#"{"subsonic-response":{"status":"ok","openSubsonicExtensions":[{"name":"octoTopSongs","versions":[1]}]}}"# + }; + write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",body.len(),body).unwrap(); + } + }); + let api = Api::new(Config { + server: format!("http://{address}/music"), + api_key: "test-key".into(), + ..Default::default() + }) + .unwrap(); + let items = api.load(&View::Discover).unwrap(); + assert_eq!(items.len(), 1); + assert_eq!(items[0].title(), "New music"); + assert_eq!(items[0].recommendation_source(), "Last.fm"); + assert_eq!(items[0].label(), "DISCOVER"); + server.join().unwrap(); + } + #[test] + fn error_does_not_echo_secrets() { + let err = envelope(serde_json::json!({"subsonic-response":{"status":"failed","error":{"code":40,"message":"secret"}}})).unwrap_err(); + assert!(!err.to_string().contains("secret")); + assert!(envelope(serde_json::json!({})).is_err()); + } + #[test] + fn auth_and_subpath_are_preserved() { + let api = Api::new(Config { + server: "https://example.com/music".into(), + username: "listener".into(), + password: "private".into(), + ..Default::default() + }) + .unwrap(); + let url = api.url("search3", &[("query", "a & b".into())]).unwrap(); + assert_eq!(url.path(), "/music/rest/search3"); + let p: std::collections::HashMap<_, _> = url.query_pairs().collect(); + assert_eq!(p["query"], "a & b"); + assert_eq!( + p["t"], + format!("{:x}", md5::compute(format!("private{}", p["s"]))) + ); + assert_ne!(url, api.url("search3", &[]).unwrap()); + } +}
A
src/app.rs
@@ -0,0 +1,2651 @@
+use crate::{ + api::Api, + artwork::Artwork, + config, + downloads::{Acquisition, Download, Phase}, + model::{Item, Song, View, home_items}, + player::{Playback, Player, PlayerEvent}, + playlists::{PlaylistChoice, PlaylistDialog, PlaylistTarget}, + theme::Theme, +}; +use anyhow::Result; +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use ratatui::widgets::TableState; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::{ + collections::HashMap, + path::PathBuf, + sync::{ + Arc, + mpsc::{self, Receiver, Sender}, + }, + time::{Duration, Instant}, +}; + +pub const NAV: &[&str] = &[ + "Home", + "Search", + "Artists", + "Songs", + "Playlists", + "Genres", + "Discover", + "Stations", + "Queue", + "History", +]; +#[derive(Clone)] +enum Job { + Load(u64, View, bool), + Star(Song, bool), + Acquisitions, + PlaylistChoices(u64), + PlaylistAdd(u64, PlaylistTarget, String), + ResolveLibrary(String, String), +} +enum Reply { + Loaded(u64, Result<Vec<Item>>), + Starred(Box<Song>, bool, Result<()>), + Acquisitions(Result<Option<Vec<Acquisition>>>), + PlaylistChoices(u64, Result<Vec<PlaylistChoice>>), + PlaylistAdded(u64, PlaylistTarget, Result<()>), + LibraryResolved(String, Result<Option<Box<Song>>>), + NowPlayingFailed(String, anyhow::Error), +} +#[derive(Default, Serialize, Deserialize)] +struct Session { + #[serde(default)] + theme: Theme, + queue: Vec<Song>, + #[serde(default)] + listening_history: Vec<Song>, + volume: u8, + #[serde(default)] + library_only: bool, +} + +pub struct App { + pub artwork: Artwork, + pub theme: Theme, + pub library_only: bool, + pub view: View, + pub items: Vec<Item>, + pub table: TableState, + pub nav: usize, + pub sidebar: bool, + pub queue: Vec<Song>, + pub current: Option<usize>, + pub position: f64, + pub duration: f64, + pub paused: bool, + pub volume: u8, + pub repeat: bool, + pub status: String, + pub input: Option<String>, + pub server_search: bool, + search_selection: Option<usize>, + pub help: bool, + pub help_scroll: u16, + pub loading: bool, + pub load_error: Option<String>, + pub quit: bool, + pub downloads: HashMap<String, Download>, + pub playlist_dialog: Option<PlaylistDialog>, + playlist_generation: u64, + library_copies: HashMap<String, Song>, + acquisition_poll_pending: bool, + next_acquisition_poll: Instant, + back_stack: Vec<(View, Vec<Item>, usize, bool)>, + listening_history: Vec<Song>, + pending_history: Option<Song>, + queue_play_tokens: Vec<String>, + history_ready: bool, + now_playing: Option<Sender<String>>, + tx: Sender<Job>, + rx: Receiver<Reply>, + generation: u64, + api: Arc<Api>, + player: Option<Box<dyn Playback>>, + last_g: Option<Instant>, + session_path: Option<PathBuf>, +} + +impl App { + /// Server requests run off the UI thread; generations discard stale navigation responses. + pub fn new(api: Arc<Api>, volume: u8) -> Self { + let (tx, jobs) = mpsc::channel(); + let (results, rx) = mpsc::channel(); + let jobs = Arc::new(std::sync::Mutex::new(jobs)); + for _ in 0..3 { + let jobs = Arc::clone(&jobs); + let api = Arc::clone(&api); + let results = results.clone(); + std::thread::spawn(move || { + loop { + let job = jobs.lock().unwrap().recv(); + let Ok(job) = job else { + break; + }; + let reply = match job { + Job::Load(id, view, library_only) => { + Reply::Loaded(id, api.load_with_mode(&view, library_only)) + } + Job::Acquisitions => Reply::Acquisitions(api.acquisitions()), + Job::ResolveLibrary(source, id) => Reply::LibraryResolved( + source, + api.library_song(&id).map(|song| song.map(Box::new)), + ), + Job::PlaylistChoices(id) => { + Reply::PlaylistChoices(id, api.playlist_choices()) + } + Job::PlaylistAdd(id, target, song) => { + let result = api.add_to_playlist(&target, &song); + Reply::PlaylistAdded(id, target, result) + } + Job::Star(song, add) => { + let result = api + .call( + if add { "star" } else { "unstar" }, + &[("id", song.id.clone())], + ) + .map(|_| ()); + Reply::Starred(Box::new(song), add, result) + } + }; + if results.send(reply).is_err() { + break; + } + } + }); + } + + let session_path = config::directory().join(format!("session-{}.json", api.session_key())); + let (now_playing, tracks) = mpsc::channel::<String>(); + let playback_api = Arc::clone(&api); + std::thread::spawn(move || { + while let Ok(id) = tracks.recv() { + // Serialize announcements and skip tracks superseded during a slow request. + let id = tracks.try_iter().last().unwrap_or(id); + if let Err(error) = playback_api.report_now_playing(&id) + && results.send(Reply::NowPlayingFailed(id, error)).is_err() + { + break; + } + } + }); + let mut app = Self::with_channels(api, volume, Some(session_path), tx, rx); + app.now_playing = Some(now_playing); + if app + .queue + .iter() + .chain(&app.listening_history) + .any(|song| song.is_external) + { + app.acquisition_poll_pending = app.tx.send(Job::Acquisitions).is_ok(); + } + app + } + + /// Share state initialization with tests without connecting test state to audio or disk. + fn with_channels( + api: Arc<Api>, + volume: u8, + session_path: Option<PathBuf>, + tx: Sender<Job>, + rx: Receiver<Reply>, + ) -> Self { + let session = session_path + .as_ref() + .and_then(|p| std::fs::read(p).ok()) + .and_then(|s| serde_json::from_slice::<Session>(&s).ok()); + let saved_volume = session.as_ref().map(|s| s.volume).unwrap_or(volume); + let saved_theme = session.as_ref().map(|s| s.theme).unwrap_or_default(); + let mut listening_history = session + .as_ref() + .map(|s| s.listening_history.clone()) + .unwrap_or_default(); + listening_history.truncate(1000); + let mut app = Self { + artwork: Artwork::default(), + theme: saved_theme, + library_only: session.as_ref().is_some_and(|s| s.library_only), + view: View::Home, + items: vec![], + table: TableState::default().with_selected(0), + nav: 0, + sidebar: false, + queue: session.map(|s| s.queue).unwrap_or_default(), + current: None, + position: 0., + duration: 0., + paused: false, + volume: saved_volume.min(100), + repeat: false, + status: "Connecting…".into(), + input: None, + server_search: false, + search_selection: None, + help: false, + help_scroll: 0, + loading: false, + load_error: None, + quit: false, + downloads: HashMap::new(), + playlist_dialog: None, + playlist_generation: 0, + library_copies: HashMap::new(), + acquisition_poll_pending: false, + next_acquisition_poll: Instant::now(), + back_stack: vec![], + listening_history, + pending_history: None, + queue_play_tokens: vec![], + history_ready: false, + now_playing: None, + tx, + rx, + generation: 0, + api, + player: None, + last_g: None, + session_path, + }; + if app.library_only { + app.prune_external_queue(); + } + app.load(); + app + } + #[cfg(test)] + pub fn for_tests() -> Self { + let api = Arc::new( + Api::new(crate::config::Config { + server: "http://127.0.0.1:1".into(), + api_key: "test-key".into(), + ..Default::default() + }) + .unwrap(), + ); + let (tx, _jobs) = mpsc::channel(); + let (_results, rx) = mpsc::channel(); + let mut app = Self::with_channels(api, 70, None, tx, rx); + app.player = Some(Box::new(crate::test_support::TestPlayback::default())); + app + } + fn load(&mut self) { + self.load_error = None; + self.generation += 1; + self.table.select(Some(0)); + if matches!(self.view, View::Home) { + self.items = home_items(); + self.loading = false; + self.status = "Choose a Home section · j/k move · Enter opens".into(); + } else if matches!(self.view, View::History) { + self.items = self + .listening_history + .iter() + .cloned() + .map(Item::Song) + .collect(); + self.filter_visible_items(); + self.loading = false; + self.status = "Recently played songs · newest first · a adds to a playlist".into(); + } else if matches!(self.view, View::Queue) { + self.items = self.queue.iter().cloned().map(Item::Song).collect(); + self.table.select(Some( + self.current + .unwrap_or(0) + .min(self.queue.len().saturating_sub(1)), + )); + self.loading = false; + } else { + self.items.clear(); + self.loading = true; + self.status = "Loading…".into(); + let _ = self.tx.send(Job::Load( + self.generation, + self.view.clone(), + self.library_only, + )); + } + } + /// Keep visited collections so backing out does not require another network call. + fn navigate(&mut self, view: View) { + self.back_stack.push(( + self.view.clone(), + self.items.clone(), + self.table.selected().unwrap_or(0), + self.library_only, + )); + self.view = view; + self.sidebar = false; + self.load(); + } + fn back(&mut self) { + if let Some((view, items, selection, library_only)) = self.back_stack.pop() { + if library_only && !self.library_only { + self.view = view; + self.load(); + return; + } + self.generation += 1; + self.loading = false; + self.view = view; + self.load_error = None; + self.items = items; + self.filter_visible_items(); + self.table.select(Some(selection)); + self.clamp_selection(); + if matches!(self.view, View::Queue) { + self.refresh_queue(); + } else if matches!(self.view, View::History) { + self.refresh_listening_history(); + } + } + } + fn refresh_queue(&mut self) { + self.sync_play_tokens(); + if matches!(self.view, View::Queue) { + self.items = self.queue.iter().cloned().map(Item::Song).collect(); + } + self.clamp_selection(); + } + /// Apply the mode again when cached or in-flight results reach the browser. + fn filter_visible_items(&mut self) { + if self.library_only { + self.items + .retain(|item| !matches!(item, Item::Song(song) if song.is_external)); + } + } + /// Keep queue indices and playback tokens attached to their retained library entries. + fn prune_external_queue(&mut self) { + self.sync_play_tokens(); + let mut current = None; + let mut index = 0; + let mut tokens = std::mem::take(&mut self.queue_play_tokens).into_iter(); + self.queue.retain(|song| { + let token = tokens.next().unwrap(); + let keep = !song.is_external; + if keep { + if self.current == Some(index) { + current = Some(self.queue_play_tokens.len()); + } + self.queue_play_tokens.push(token); + } + index += 1; + keep + }); + if self.current.is_some() && current.is_none() { + self.command(json!(["stop"])); + self.pending_history = None; + self.history_ready = false; + self.position = 0.; + self.duration = 0.; + self.paused = false; + } + self.current = current; + } + fn toggle_library_only(&mut self) { + self.library_only = !self.library_only; + if self.library_only { + self.prune_external_queue(); + } + self.load(); + self.status = if self.library_only { + "Library only · m includes online songs".into() + } else { + "Library and online songs · m switches to library only".into() + }; + self.save(); + } + fn clamp_selection(&mut self) { + self.table.select(Some( + self.table + .selected() + .unwrap_or(0) + .min(self.items.len().saturating_sub(1)), + )); + } + fn move_selection(&mut self, delta: isize) { + if self.sidebar { + self.nav = self.nav.saturating_add_signed(delta).min(NAV.len() - 1); + } else { + self.table.select(Some( + self.table + .selected() + .unwrap_or(0) + .saturating_add_signed(delta) + .min(self.items.len().saturating_sub(1)), + )); + } + } + fn select_nav(&mut self) { + let view = match self.nav { + 0 => View::Home, + 2 => View::Artists, + 1 => { + self.server_search = true; + self.input = Some(String::new()); + self.sidebar = false; + return; + } + 3 => View::Songs { offset: 0 }, + 4 => View::Playlists, + 5 => View::Genres, + 6 => View::Discover, + 7 => View::Stations, + 8 => View::Queue, + _ => View::History, + }; + self.navigate(view); + } + fn open(&mut self) { + if self.sidebar { + self.select_nav(); + return; + } + let Some(item) = self.items.get(self.table.selected().unwrap_or(0)).cloned() else { + return; + }; + match item { + Item::HomeSection(section) => self.navigate(section.view()), + Item::Song(_) => { + let index = self.table.selected().unwrap_or(0); + if matches!(self.view, View::Queue) { + self.play(index); + } else { + let songs: Vec<_> = self + .items + .iter() + .filter_map(|i| { + if let Item::Song(s) = i + && (!self.library_only || !s.is_external) + { + Some(s.clone()) + } else { + None + } + }) + .collect(); + self.queue = songs; + self.queue_play_tokens.clear(); + self.play(index); + self.save(); + } + } + Item::Album { id, .. } => self.navigate(View::Album(id)), + Item::Artist { id, .. } => self.navigate(View::Artist(id)), + Item::Playlist { id, .. } => self.navigate(View::Playlist(id)), + Item::Genre(g) => self.navigate(View::Genre(g)), + Item::Station { id, .. } => self.navigate(View::Station(id)), + } + } + fn selected_song(&self) -> Option<Song> { + match self.items.get(self.table.selected().unwrap_or(0)) { + Some(Item::Song(s)) if !self.library_only || !s.is_external => Some(s.clone()), + _ => None, + } + } + /// Every queue occurrence owns a stable play identity, even when duplicate songs are reordered. + fn sync_play_tokens(&mut self) { + self.queue_play_tokens.truncate(self.queue.len()); + while self.queue_play_tokens.len() < self.queue.len() { + self.queue_play_tokens + .push(format!("{:032x}.0", rand::random::<u128>())); + } + } + /// Resolve streams only at playback time so restored queues never reuse expired tokens. + fn play(&mut self, index: usize) { + let Some(song) = self.queue.get(index).cloned() else { + return; + }; + if self.library_only && song.is_external { + self.status = "Library-only mode: external playback is disabled. Press m to include online songs.".into(); + return; + } + if self.player.is_none() { + match Player::start(self.volume) { + Ok(player) => self.player = Some(Box::new(player)), + Err(e) => { + self.status = e.to_string(); + return; + } + } + } + if matches!(self.view, View::Queue) && self.table.selected() == self.current { + self.table.select(Some(index)); + } + self.sync_play_tokens(); + self.pending_history = Some(song.clone()); + self.history_ready = false; + self.current = Some(index); + self.position = 0.; + self.duration = song.duration as f64; + self.paused = false; + self.status = format!("{} · {}", song.title, song.artist); + match self.api.url( + "stream", + &[ + ("id", song.id), + ("format", "raw".into()), + ("octoPlay", self.queue_play_tokens[index].clone()), + ], + ) { + Ok(url) => { + self.command(json!(["loadfile", url.as_str(), "replace"])); + self.command(json!(["set_property", "pause", false])); + } + Err(e) => { + self.status = e.to_string(); + self.current = None; + self.pending_history = None; + } + } + } + fn command(&mut self, value: serde_json::Value) { + if let Some(player) = &mut self.player + && let Err(e) = player.command(value) + { + self.status = e.to_string(); + } + } + fn next(&mut self, delta: isize) { + if let Some(index) = self.current { + let next = index as isize + delta; + if next >= 0 && (next as usize) < self.queue.len() { + self.play(next as usize); + } else if self.repeat && !self.queue.is_empty() { + self.play(0); + } else { + self.current = None; + self.pending_history = None; + self.history_ready = false; + self.command(json!(["stop"])); + self.status = "Queue finished".into(); + } + } else if !self.queue.is_empty() { + self.play(0); + } + } + /// Apply background results and playback events between terminal frames. + pub fn tick(&mut self) { + while let Ok(reply) = self.rx.try_recv() { + match reply { + Reply::Loaded(id, result) if id == self.generation => { + self.loading = false; + match result { + Ok(mut items) => { + for item in &mut items { + Self::apply_library_item(item, &self.library_copies); + } + self.items = items; + self.filter_visible_items(); + self.find_in_view(); + self.load_error = None; + self.status = format!( + "{} results · Enter opens or plays · ? help", + self.items.len() + ); + } + Err(e) => { + self.load_error = Some(e.to_string()); + self.status = e.to_string(); + } + } + } + Reply::LibraryResolved(source, result) => { + if let Some(download) = self.downloads.get_mut(&source) { + download.resolve_pending = false; + download.next_resolve = Instant::now() + + Duration::from_secs(if result.is_err() { 15 } else { 5 }); + } + if let Ok(Some(song)) = result { + self.install_library_copy(source, *song); + } + } + Reply::NowPlayingFailed(id, error) + if self + .current + .and_then(|index| self.queue.get(index)) + .is_some_and(|song| song.id == id) => + { + self.status = format!("Now Playing report failed ({error})"); + } + Reply::PlaylistChoices(id, result) => { + if let Some(dialog) = &mut self.playlist_dialog + && dialog.id == id + { + dialog.loading = false; + match result { + Ok(choices) => dialog.choices = choices, + Err(e) => dialog.error = Some(e.to_string()), + } + } + } + Reply::PlaylistAdded(id, target, result) => { + if self + .playlist_dialog + .as_ref() + .is_some_and(|dialog| dialog.id == id) + { + match result { + Ok(()) => { + self.playlist_dialog = None; + self.status = format!("Song added to playlist: {}", target.name()); + if matches!(self.view, View::Playlists) + || matches!((&self.view,&target),(View::Playlist(view_id),PlaylistTarget::Existing {id,..}) if view_id==id) + { + self.load(); + } + } + Err(e) => { + let dialog = self.playlist_dialog.as_mut().unwrap(); + dialog.saving = false; + dialog.error = Some(e.to_string()); + } + } + } + } + Reply::Starred(song, add, result) => match result { + Ok(()) => { + if song.is_external && add { + self.downloads + .entry(song.id.clone()) + .or_insert_with(Download::requesting) + .phase = Phase::Requested; + self.next_acquisition_poll = Instant::now(); + } + for item in &mut self.items { + if let Item::Song(s) = item + && s.id == song.id + { + s.starred = add.then(|| "starred".into()); + } + } + for s in &mut self.queue { + if s.id == song.id { + s.starred = add.then(|| "starred".into()); + } + } + self.save(); + self.status = if song.is_external && add { + "Download requested; the library copy will be resolved automatically" + .into() + } else { + "Favorite updated".into() + }; + } + Err(e) => { + if let Some(download) = self.downloads.get_mut(&song.id) { + download.phase = Phase::Failed; + } + self.status = e.to_string(); + } + }, + Reply::Acquisitions(result) => { + self.acquisition_poll_pending = false; + self.next_acquisition_poll = + Instant::now() + Duration::from_secs(if result.is_err() { 15 } else { 3 }); + match result { + Ok(Some(entries)) => { + // Recover completed acquisitions for external entries restored in the saved queue. + for song in self + .queue + .iter() + .chain(&self.listening_history) + .filter(|song| song.is_external) + { + if self.downloads.contains_key(&song.id) { + continue; + } + let id = song.id.strip_prefix("find:").unwrap_or(&song.id); + if let Some(entry) = entries + .iter() + .filter(|e| e.id == id) + .max_by_key(|e| e.started_at.as_deref().unwrap_or("")) + { + let mut download = Download::requesting(); + download.update(entry); + self.downloads.insert(song.id.clone(), download); + } + } + for (id, download) in &mut self.downloads { + if !download.pollable() { + continue; + } + let id = id.strip_prefix("find:").unwrap_or(id); + if let Some(entry) = entries + .iter() + .filter(|entry| entry.id == id) + .max_by_key(|entry| entry.started_at.as_deref().unwrap_or("")) + { + download.update(entry); + } else if download.last_seen.elapsed() > Duration::from_secs(60) { + download.unavailable = true; + } + } + } + Ok(None) => { + for download in self.downloads.values_mut().filter(|d| d.pollable()) { + download.unavailable = true; + } + } + Err(_) => {} + } + } + _ => {} + } + } + if !self.acquisition_poll_pending + && Instant::now() >= self.next_acquisition_poll + && self.downloads.values().any(Download::pollable) + { + self.acquisition_poll_pending = self.tx.send(Job::Acquisitions).is_ok(); + } + for (source, download) in &mut self.downloads { + if download.phase == Phase::Done + && !download.library_resolved + && !download.resolve_pending + && Instant::now() >= download.next_resolve + { + let id = download + .library_id + .clone() + .unwrap_or_else(|| source.strip_prefix("find:").unwrap_or(source).into()); + download.resolve_pending = self + .tx + .send(Job::ResolveLibrary(source.clone(), id)) + .is_ok(); + } + } + let events: Vec<_> = self + .player + .as_ref() + .map(|p| p.drain_events()) + .unwrap_or_default(); + for event in events { + match event { + PlayerEvent::Loaded => self.history_ready = true, + PlayerEvent::Position(p) => { + self.position = p.max(0.); + if p > 0. + && self.history_ready + && !self.paused + && let Some(song) = self.pending_history.take() + { + if !song.is_external + && !song.id.is_empty() + && let Some(reporter) = &self.now_playing + { + let _ = reporter.send(song.id.clone()); + } + self.record_play(song); + } + } + PlayerEvent::Duration(d) => self.duration = d.max(0.), + PlayerEvent::Paused(p) => self.paused = p, + PlayerEvent::Finished => self.next(1), + PlayerEvent::Error(e) => { + self.status = e; + self.current = None; + self.pending_history = None; + self.history_ready = false; + } + } + } + let cover = self + .current + .and_then(|i| self.queue.get(i)) + .and_then(|s| Item::Song(s.clone()).cover()); + self.artwork.set_background(self.theme.palette().bg); + self.artwork.update(cover); + } + + /// Keep recently heard songs unique and newest first, independently of the playback queue. + fn record_play(&mut self, mut song: Song) { + if let Some(library) = self.library_copies.get(&song.id) { + song = library.clone(); + } + self.listening_history + .retain(|previous| previous.id != song.id); + self.listening_history.insert(0, song); + self.listening_history.truncate(1000); + if matches!(self.view, View::History) { + self.refresh_listening_history(); + } + self.save(); + } + fn refresh_listening_history(&mut self) { + let selected = self.selected_song().map(|s| s.id); + self.items = self + .listening_history + .iter() + .cloned() + .map(Item::Song) + .collect(); + self.filter_visible_items(); + self.table.select(Some( + selected + .and_then(|id| { + self.items + .iter() + .position(|item| matches!(item, Item::Song(song) if song.id == id)) + }) + .unwrap_or(0), + )); + } + fn apply_library_item(item: &mut Item, copies: &HashMap<String, Song>) { + if let Item::Song(song) = item + && let Some(library) = copies.get(&song.id) + { + *song = library.clone(); + } + } + /// Replace every cached copy by server ID, preserving queue order and the active mpv stream. + fn install_library_copy(&mut self, source: String, mut song: Song) { + if song.is_external || song.id.is_empty() { + return; + } + // Keep recommendation provenance; it is independent of where playback comes from. + if song.octo_suggested_by.is_none() { + song.octo_suggested_by = self + .queue + .iter() + .find(|s| s.id == source) + .and_then(|s| s.octo_suggested_by.clone()) + .or_else(|| { + self.items.iter().find_map(|item| match item { + Item::Song(s) if s.id == source => s.octo_suggested_by.clone(), + _ => None, + }) + }); + } + self.library_copies.insert(source.clone(), song.clone()); + if let Some(download) = self.downloads.get_mut(&source) { + download.library_resolved = true; + } + for item in &mut self.items { + Self::apply_library_item(item, &self.library_copies); + } + for queued in &mut self.queue { + if let Some(library) = self.library_copies.get(&queued.id) { + *queued = library.clone(); + } + } + for played in &mut self.listening_history { + if let Some(library) = self.library_copies.get(&played.id) { + *played = library.clone(); + } + } + let mut seen = std::collections::HashSet::new(); + self.listening_history + .retain(|song| seen.insert(song.id.clone())); + if let Some(pending) = &mut self.pending_history + && let Some(library) = self.library_copies.get(&pending.id) + { + *pending = library.clone(); + } + for (_, items, _, _) in &mut self.back_stack { + for item in items { + Self::apply_library_item(item, &self.library_copies); + } + } + if let Some(dialog) = &mut self.playlist_dialog + && dialog.song.id == source + { + dialog.song = song; + if let Some(target) = dialog.pending_target.take() + && self + .tx + .send(Job::PlaylistAdd(dialog.id, target, dialog.song.id.clone())) + .is_err() + { + dialog.saving = false; + dialog.error = Some("Cannot add song: server worker unavailable".into()); + } + } + self.save(); + } + /// Persist only song metadata; signed stream URLs and credentials never enter the session. + pub fn save(&mut self) { + let Some(path) = &self.session_path else { + return; + }; + let result = (|| -> Result<()> { + std::fs::create_dir_all(path.parent().unwrap())?; + let temp = path.with_extension(format!("json.{}.tmp", std::process::id())); + std::fs::write( + &temp, + serde_json::to_vec(&Session { + queue: self.queue.clone(), + listening_history: self.listening_history.clone(), + theme: self.theme, + library_only: self.library_only, + volume: self.volume, + })?, + )?; + std::fs::rename(temp, path)?; + Ok(()) + })(); + if result.is_err() { + self.status = "Could not save queue to configuration directory".into(); + } + } + /// Capture the song when opening the modal so playback and browsing cannot change its target. + fn open_playlist_dialog(&mut self) { + let Some(song) = self.selected_song() else { + self.status = "Select a song to add to a playlist".into(); + return; + }; + self.playlist_generation += 1; + let mut dialog = PlaylistDialog::new(self.playlist_generation, song); + if self.tx.send(Job::PlaylistChoices(dialog.id)).is_err() { + dialog.loading = false; + dialog.error = Some("Cannot load playlists: server worker unavailable".into()); + } + self.playlist_dialog = Some(dialog); + } + /// Modal input stays isolated from browsing, playback shortcuts and duplicate submissions. + fn playlist_key(&mut self, key: KeyEvent) { + let dialog = self.playlist_dialog.as_mut().unwrap(); + if dialog.saving { + if key.code == KeyCode::Esc && dialog.pending_target.is_some() { + self.playlist_dialog = None; + } + return; + } + if let Some(name) = &mut dialog.new_name { + match key.code { + KeyCode::Esc => { + dialog.new_name = None; + dialog.error = None; + return; + } + KeyCode::Backspace => { + name.pop(); + return; + } + KeyCode::Char(c) => { + name.push(c); + dialog.error = None; + return; + } + KeyCode::Enter => {} + _ => return, + } + } else { + match key.code { + KeyCode::Esc | KeyCode::Char('q') => { + self.playlist_dialog = None; + return; + } + KeyCode::Down | KeyCode::Char('j') => { + dialog.selected = (dialog.selected + 1).min(dialog.choices.len()); + dialog.error = None; + return; + } + KeyCode::Up | KeyCode::Char('k') => { + dialog.selected = dialog.selected.saturating_sub(1); + dialog.error = None; + return; + } + KeyCode::Char('g') | KeyCode::Home => { + dialog.selected = 0; + return; + } + KeyCode::Char('G') | KeyCode::End => { + dialog.selected = dialog.choices.len(); + return; + } + KeyCode::Char('n') => { + dialog.new_name = Some(String::new()); + dialog.error = None; + return; + } + KeyCode::Enter if dialog.selected == 0 => { + dialog.new_name = Some(String::new()); + dialog.error = None; + return; + } + KeyCode::Enter => {} + _ => return, + } + } + let target = if let Some(name) = &dialog.new_name { + let name = name.trim(); + if name.is_empty() { + dialog.error = Some("Enter a playlist name".into()); + return; + } + PlaylistTarget::New { name: name.into() } + } else { + let Some(choice) = dialog.choices.get(dialog.selected.saturating_sub(1)) else { + return; + }; + if let Some(error) = choice.addition_error() { + dialog.error = Some(error.into()); + return; + } + PlaylistTarget::Existing { + id: choice.id.clone(), + name: choice.name.clone(), + } + }; + if self + .downloads + .get(&dialog.song.id) + .is_some_and(|d| d.phase == Phase::Done && !d.library_resolved) + { + dialog.pending_target = Some(target); + dialog.saving = true; + dialog.error = None; + return; + } + if self + .tx + .send(Job::PlaylistAdd(dialog.id, target, dialog.song.id.clone())) + .is_err() + { + dialog.error = Some("Cannot add song: server worker unavailable".into()); + return; + } + dialog.saving = true; + dialog.error = None; + } + /// Find the first matching loaded row without changing the collection or calling the server. + fn find_in_view(&mut self) { + if self.server_search { + return; + } + let Some(query) = &self.input else { + return; + }; + let query = query.to_lowercase(); + if query.is_empty() { + self.table.select(self.search_selection); + self.clamp_selection(); + } else if let Some(index) = self.items.iter().position(|item| { + item.title().to_lowercase().contains(&query) + || item.detail().to_lowercase().contains(&query) + }) { + self.table.select(Some(index)); + } + } + /// Input mode consumes text before normal Vim-style command dispatch. + pub fn key(&mut self, key: KeyEvent) { + if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) { + self.quit = true; + return; + } + if self.playlist_dialog.is_some() { + self.playlist_key(key); + return; + } + if let Some(input) = &mut self.input { + match key.code { + KeyCode::Esc => { + self.input = None; + if !self.server_search { + self.table.select(self.search_selection); + self.clamp_selection(); + } + } + KeyCode::Enter => { + let query = input.trim().to_owned(); + self.input = None; + if self.server_search && !query.is_empty() { + self.navigate(View::Search(query)); + } + } + KeyCode::Backspace => { + input.pop(); + self.find_in_view(); + } + KeyCode::Char(c) => { + input.push(c); + self.find_in_view(); + } + _ => {} + } + return; + } + if self.help { + match key.code { + KeyCode::Esc | KeyCode::Char('?') | KeyCode::Char('q') => self.help = false, + KeyCode::Down | KeyCode::Char('j') => { + self.help_scroll = self.help_scroll.saturating_add(1) + } + KeyCode::Up | KeyCode::Char('k') => { + self.help_scroll = self.help_scroll.saturating_sub(1) + } + KeyCode::PageDown => self.help_scroll = self.help_scroll.saturating_add(10), + KeyCode::PageUp => self.help_scroll = self.help_scroll.saturating_sub(10), + _ => {} + } + return; + } + match key.code { + KeyCode::Char('q') => self.quit = true, + KeyCode::Char('?') => { + self.help = true; + self.help_scroll = 0; + } + KeyCode::Char('/') => { + self.server_search = false; + self.search_selection = self.table.selected(); + self.input = Some(String::new()); + self.sidebar = false; + } + KeyCode::Tab => self.sidebar = !self.sidebar, + KeyCode::Char('h') | KeyCode::Left => { + if self.sidebar { + self.back(); + } else { + self.sidebar = true; + } + } + KeyCode::Char('l') | KeyCode::Right | KeyCode::Enter => self.open(), + KeyCode::Esc | KeyCode::Backspace => self.back(), + KeyCode::Char('j') | KeyCode::Down => self.move_selection(1), + KeyCode::Char('k') | KeyCode::Up => self.move_selection(-1), + KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => { + self.move_selection(10) + } + KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => { + self.move_selection(-10) + } + KeyCode::Char('G') => { + if self.sidebar { + self.nav = NAV.len() - 1; + } else { + self.table.select(Some(self.items.len().saturating_sub(1))); + } + } + KeyCode::Char('g') => { + if self + .last_g + .is_some_and(|t| t.elapsed() < Duration::from_millis(600)) + { + if self.sidebar { + self.nav = 0; + } else { + self.table.select(Some(0)); + } + self.last_g = None; + } else { + self.last_g = Some(Instant::now()); + } + } + KeyCode::Char(c @ '0'..='9') => { + self.nav = (c as u8 - b'0') as usize; + self.select_nav(); + } + KeyCode::Char(' ') => { + if self.current.is_some() { + self.paused = !self.paused; + self.command(json!(["set_property", "pause", self.paused])); + } else if !self.queue.is_empty() { + self.play(0); + } + } + KeyCode::Char('L') => self.next(1), + KeyCode::Char('H') => self.next(-1), + KeyCode::Char(']') | KeyCode::Char('[') => { + let amount = if key.code == KeyCode::Char(']') { + 10. + } else { + -10. + }; + self.position = (self.position + amount).clamp(0., self.duration.max(0.)); + self.command(json!(["seek", amount, "relative"])); + } + KeyCode::Char('=') | KeyCode::Char('-') => { + self.volume = self + .volume + .saturating_add_signed(if key.code == KeyCode::Char('=') { + 5 + } else { + -5 + }) + .min(100); + self.command(json!(["set_property", "volume", self.volume])); + self.save(); + } + KeyCode::Char('m') => self.toggle_library_only(), + KeyCode::Char('i') => { + if let Some(song) = self.selected_song() { + if let Some(id) = song.artist_id.filter(|id| !id.trim().is_empty()) { + self.navigate(View::Artist(id)); + } else if !song.artist.trim().is_empty() { + self.navigate(View::ArtistByName(song.artist.trim().into())); + } else { + self.status = "No artist information is available for this song.".into(); + } + } else { + self.status = "Select a song to open its artist.".into(); + } + } + KeyCode::Char('a') => self.open_playlist_dialog(), + KeyCode::Char('e') => { + if let Some(song) = self.selected_song() { + self.queue.push(song); + self.refresh_queue(); + self.save(); + self.status = "Added to queue".into(); + } + } + KeyCode::Char('A') => { + self.queue.extend(self.items.iter().filter_map(|i| { + if let Item::Song(s) = i + && (!self.library_only || !s.is_external) + { + Some(s.clone()) + } else { + None + } + })); + self.refresh_queue(); + self.save(); + self.status = "Added visible tracks to queue".into(); + } + KeyCode::Char('x') if matches!(self.view, View::Queue) => { + let i = self.table.selected().unwrap_or(0); + if i < self.queue.len() { + self.sync_play_tokens(); + self.queue_play_tokens.remove(i); + self.queue.remove(i); + if let Some(current) = self.current { + if i == current { + self.current = None; + self.command(json!(["stop"])); + } else if i < current { + self.current = Some(current - 1); + } + } + self.refresh_queue(); + self.save(); + } + } + KeyCode::Char('J') | KeyCode::Char('K') if matches!(self.view, View::Queue) => { + let i = self.table.selected().unwrap_or(0); + let j = i.saturating_add_signed(if key.code == KeyCode::Char('J') { + 1 + } else { + -1 + }); + if i < self.queue.len() && j < self.queue.len() { + self.sync_play_tokens(); + self.queue_play_tokens.swap(i, j); + self.queue.swap(i, j); + if self.current == Some(i) { + self.current = Some(j); + } else if self.current == Some(j) { + self.current = Some(i); + } + self.refresh_queue(); + self.table.select(Some(j)); + self.save(); + } + } + KeyCode::Char('f') | KeyCode::Char('+') | KeyCode::Char('d') => { + if let Some(song) = self.selected_song() { + if key.code == KeyCode::Char('d') && !song.is_external { + self.status = "Already in library".into(); + return; + } + let download = song.is_external + && matches!(key.code, KeyCode::Char('d') | KeyCode::Char('+')); + let add = matches!(key.code, KeyCode::Char('+') | KeyCode::Char('d')) + || song.starred.is_none(); + if song.is_external && add { + if let Some(existing) = self.downloads.get(&song.id) { + if existing.in_flight() && !existing.unavailable { + self.status = format!("Download: {}", existing.detail()); + return; + } + if existing.phase == Phase::Done { + self.status = + "Downloaded; waiting for the indexed library copy".into(); + return; + } + } + self.downloads + .insert(song.id.clone(), Download::requesting()); + } + if self.tx.send(Job::Star(song.clone(), add)).is_err() { + if let Some(download) = self.downloads.get_mut(&song.id) { + download.phase = Phase::Failed; + } + self.status = "Could not send request to server worker".into(); + return; + } + self.status = if download { + "Requesting download to server library…" + } else { + "Updating server…" + } + .into(); + } + } + KeyCode::Char('r') => { + if let Some(song) = self.selected_song() { + self.navigate(View::Radio(song.id)); + } + } + KeyCode::Char('R') => self.load(), + KeyCode::Char('t') => { + self.theme = self.theme.next(); + self.save(); + self.status = format!("Theme: {} · t cycles themes", self.theme.name()); + } + KeyCode::Char('s') => { + use rand::seq::SliceRandom; + self.sync_play_tokens(); + let start = self.current.map_or(0, |current| current + 1); + let mut entries: Vec<_> = self + .queue + .drain(start..) + .zip(self.queue_play_tokens.drain(start..)) + .collect(); + entries.shuffle(&mut rand::thread_rng()); + for (song, token) in entries { + self.queue.push(song); + self.queue_play_tokens.push(token); + } + self.refresh_queue(); + self.save(); + self.status = "Shuffled upcoming queue".into(); + } + KeyCode::Char('z') => { + self.repeat = !self.repeat; + } + KeyCode::Char('o') => { + if let View::Albums { kind, offset } = &mut self.view { + let kinds = [ + "newest", + "alphabeticalByName", + "alphabeticalByArtist", + "frequent", + "recent", + "random", + ]; + let index = kinds.iter().position(|k| k == kind).unwrap_or(0); + *kind = kinds[(index + 1) % kinds.len()].into(); + *offset = 0; + self.load(); + } + } + KeyCode::Char('>') | KeyCode::Char('<') => { + let forward = key.code == KeyCode::Char('>'); + match &mut self.view { + View::Albums { offset, .. } | View::Songs { offset } => { + *offset = if forward { + offset.saturating_add(100) + } else { + offset.saturating_sub(100) + }; + self.load(); + } + _ => {} + } + } + _ => {} + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn key(app: &mut App, c: char) { + app.key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)); + } + #[test] + fn play_tokens_follow_queue_entries_and_survive_replay_and_reorder() { + let mut app = App::for_tests(); + app.queue = crate::test_support::songs(); + app.sync_play_tokens(); + let playback = crate::test_support::TestPlayback::default(); + let commands = playback.commands.clone(); + app.player = Some(Box::new(playback)); + let tokens = app.queue_play_tokens.clone(); + assert_ne!(tokens[0], tokens[1]); + app.play(0); + app.play(0); + assert_eq!(app.queue_play_tokens, tokens); + let commands = commands.lock().unwrap(); + let loads: Vec<_> = commands.iter().filter(|c| c[0] == "loadfile").collect(); + assert_eq!(loads.len(), 2); + for load in loads { + let url = reqwest::Url::parse(load[1].as_str().unwrap()).unwrap(); + assert!(url.query_pairs().any(|(k, v)| k == "format" && v == "raw")); + assert!( + url.query_pairs() + .any(|(k, v)| k == "octoPlay" && v == tokens[0]) + ); + } + drop(commands); + app.view = View::Queue; + app.refresh_queue(); + app.table.select(Some(0)); + key(&mut app, 'J'); + assert_eq!(app.queue_play_tokens[1], tokens[0]); + app.table.select(Some(0)); + key(&mut app, 'x'); + assert_eq!(app.queue_play_tokens[0], tokens[0]); + key(&mut app, 's'); + assert_eq!(app.queue.len(), app.queue_play_tokens.len()); + for token in &app.queue_play_tokens { + assert!(tokens.contains(token)); + } + } + + #[test] + fn artwork_follows_playback_independently_of_cursor_and_view() { + let mut app = App::for_tests(); + app.artwork.enabled = true; + app.queue = crate::test_support::songs(); + app.items = app.queue.iter().cloned().map(Item::Song).collect(); + app.table.select(Some(2)); + app.tick(); + assert!(app.artwork.title.is_empty()); + + app.play(0); + app.tick(); + assert_eq!(app.artwork.title, "Track 0"); + key(&mut app, 'j'); + app.tick(); + assert_eq!(app.artwork.title, "Track 0"); + app.sidebar = true; + app.tick(); + assert_eq!(app.artwork.title, "Track 0"); + app.view = View::Albums { + kind: "newest".into(), + offset: 0, + }; + app.items = vec![Item::Album { + id: "other".into(), + name: "Other album".into(), + artist: "Artist".into(), + cover_art: Some("other-cover".into()), + }]; + app.table.select(Some(0)); + app.sidebar = false; + app.paused = true; + app.tick(); + assert_eq!(app.artwork.title, "Track 0"); + + app.play(1); + app.tick(); + assert_eq!(app.artwork.title, "Track 1"); + app.current = None; + app.tick(); + assert!(app.artwork.title.is_empty()); + assert!(app.artwork.protocol.is_none()); + } + + #[test] + fn artist_shortcut_uses_song_id_or_name_and_preserves_playback_and_back_navigation() { + let mut app = App::for_tests(); + let song: Song = serde_json::from_value( + json!({"id":"song","title":"Selected","artist":"Artist","artistId":"artist-id"}), + ) + .unwrap(); + app.queue = crate::test_support::songs(); + app.current = Some(1); + app.view = View::Search("Selected".into()); + app.items = vec![Item::Song(song)]; + app.table.select(Some(0)); + key(&mut app, 'i'); + assert!(matches!(&app.view, View::Artist(id) if id == "artist-id")); + assert_eq!(app.current, Some(1)); + assert_eq!(app.queue.len(), 8); + app.back(); + assert!(matches!(&app.view, View::Search(query) if query == "Selected")); + assert_eq!(app.selected_song().unwrap().id, "song"); + if let Item::Song(song) = &mut app.items[0] { + song.artist_id = None; + } + key(&mut app, 'i'); + assert!(matches!(&app.view, View::ArtistByName(name) if name == "Artist")); + app.back(); + if let Item::Song(song) = &mut app.items[0] { + song.artist.clear(); + } + key(&mut app, 'i'); + assert!(app.status.contains("No artist information")); + assert!(matches!(app.view, View::Search(_))); + app.items.clear(); + key(&mut app, 'i'); + assert!(app.status.contains("Select a song")); + } + + #[test] + fn library_mode_filters_all_server_views_after_resolving_downloaded_copies() { + let views = [ + View::Search("test".into()), + View::Songs { offset: 0 }, + View::Album("album".into()), + View::Artist("artist".into()), + View::ArtistByName("Artist".into()), + View::Playlist("playlist".into()), + View::Discover, + View::Radio("seed".into()), + View::Station("station".into()), + View::Genre("Rock".into()), + ]; + for view in views { + let mut app = App::for_tests(); + app.library_only = true; + let songs = crate::test_support::songs(); + app.library_copies + .insert(songs[4].id.clone(), songs[1].clone()); + let (tx, rx) = mpsc::channel(); + app.rx = rx; + app.navigate(view); + tx.send(Reply::Loaded( + app.generation, + Ok(vec![ + Item::Song(songs[0].clone()), + Item::Song(songs[4].clone()), + Item::Song(songs[5].clone()), + Item::Artist { + id: "artist".into(), + name: "Artist".into(), + }, + ]), + )) + .unwrap(); + app.tick(); + assert_eq!(app.items.len(), 3); + assert!(matches!(&app.items[0],Item::Song(song) if song.id == songs[0].id)); + assert!(matches!(&app.items[1],Item::Song(song) if song.id == songs[1].id)); + assert!(matches!(&app.items[2], Item::Artist { .. })); + } + } + + #[test] + fn enabling_library_mode_preserves_local_playback_and_stops_external_playback() { + for current in [0, 3] { + let mut app = App::for_tests(); + let songs = crate::test_support::songs(); + app.queue = vec![ + songs[4].clone(), + songs[0].clone(), + songs[5].clone(), + songs[1].clone(), + ]; + let playback = crate::test_support::TestPlayback::default(); + let commands = playback.commands.clone(); + app.player = Some(Box::new(playback)); + app.play(current); + let tokens = app.queue_play_tokens.clone(); + commands.lock().unwrap().clear(); + key(&mut app, 'm'); + assert!(app.library_only); + assert_eq!( + app.queue + .iter() + .map(|song| song.id.as_str()) + .collect::<Vec<_>>(), + ["track-0", "track-1"] + ); + assert_eq!( + app.queue_play_tokens, + vec![tokens[1].clone(), tokens[3].clone()] + ); + if current == 3 { + assert_eq!(app.current, Some(1)); + assert!(commands.lock().unwrap().is_empty()); + } else { + assert_eq!(app.current, None); + assert!(app.pending_history.is_none()); + assert_eq!(*commands.lock().unwrap(), vec![json!(["stop"])]); + } + commands.lock().unwrap().clear(); + app.queue.push(songs[4].clone()); + app.play(2); + assert!(commands.lock().unwrap().is_empty()); + assert!(app.status.contains("external playback is disabled")); + } + } + + #[test] + fn library_mode_filters_cached_history_and_ignores_results_from_before_toggle() { + let mut app = App::for_tests(); + let songs = crate::test_support::songs(); + app.listening_history = songs.clone(); + app.view = View::Search("test".into()); + app.items = songs.iter().cloned().map(Item::Song).collect(); + app.table.select(Some(7)); + app.navigate(View::Home); + key(&mut app, 'm'); + app.back(); + assert_eq!(app.items.len(), 4); + assert_eq!(app.table.selected(), Some(3)); + key(&mut app, '9'); + assert_eq!(app.items.len(), 4); + assert_eq!(app.listening_history.len(), 8); + app.table.select(Some(2)); + app.refresh_listening_history(); + assert_eq!(app.selected_song().unwrap().id, "track-2"); + key(&mut app, 'm'); + assert_eq!(app.items.len(), 8); + + let (tx, rx) = mpsc::channel(); + app.rx = rx; + app.navigate(View::Search("test".into())); + let old = app.generation; + key(&mut app, 'm'); + tx.send(Reply::Loaded( + old, + Ok(songs.iter().cloned().map(Item::Song).collect()), + )) + .unwrap(); + app.tick(); + assert!(app.items.is_empty()); + assert!(app.loading); + tx.send(Reply::Loaded( + app.generation, + Ok(songs.into_iter().map(Item::Song).collect()), + )) + .unwrap(); + app.tick(); + assert_eq!(app.items.len(), 4); + } + + #[test] + fn backing_into_library_only_cache_after_disabling_mode_fetches_online_results_again() { + let mut app = App::for_tests(); + app.library_only = true; + app.view = View::Search("artist".into()); + app.items = vec![Item::Song(crate::test_support::songs()[0].clone())]; + app.navigate(View::Home); + key(&mut app, 'm'); + let (tx, rx) = mpsc::channel(); + app.tx = tx; + app.back(); + assert!(matches!( + rx.try_recv().unwrap(), + Job::Load(_, View::Search(_), false) + )); + assert!(app.loading); + } + + #[test] + fn library_mode_is_saved_and_restored_per_session_without_losing_history() { + let mut app = App::for_tests(); + let directory = + std::env::temp_dir().join(format!("octo-mode-test-{:x}", rand::random::<u64>())); + let path = directory.join("session.json"); + app.session_path = Some(path.clone()); + app.queue = crate::test_support::songs(); + app.listening_history = crate::test_support::songs(); + key(&mut app, 'm'); + let (tx, _) = mpsc::channel(); + let (_, rx) = mpsc::channel(); + let mut restored = App::with_channels(app.api.clone(), 70, Some(path), tx, rx); + assert!(restored.library_only); + assert_eq!(restored.queue.len(), 4); + assert_eq!(restored.listening_history.len(), 8); + assert!(restored.current.is_none()); + key(&mut restored, '9'); + assert_eq!(restored.items.len(), 4); + key(&mut restored, 'm'); + assert_eq!(restored.items.len(), 8); + std::fs::remove_dir_all(directory).unwrap(); + let old: Session = serde_json::from_value(json!({"queue":[],"volume":70})).unwrap(); + assert!(!old.library_only); + } + + #[test] + fn home_opens_offline_and_keeps_number_shortcuts() { + let mut app = App::for_tests(); + assert!(matches!(app.view, View::Home)); + assert!(!app.loading); + assert_eq!(app.items[0].title(), "Recently played"); + // Returning Home is local even if a previous server request is outstanding. + key(&mut app, '3'); + assert!(matches!(app.view, View::Songs { .. })); + key(&mut app, '0'); + assert!(matches!(app.view, View::Home)); + assert!(!app.loading); + key(&mut app, '2'); + assert!(matches!(app.view, View::Artists)); + key(&mut app, '1'); + assert_eq!(app.input.as_deref(), Some("")); + assert!(app.server_search); + app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + for c in '1'..='9' { + key(&mut app, c); + assert_eq!(app.nav, c.to_digit(10).unwrap() as usize); + if app.input.is_some() { + app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + } + } + assert!(matches!(app.view, View::History)); + } + #[test] + fn home_album_shelves_support_paging_and_back() { + let mut app = App::for_tests(); + for (index, kind) in [ + (0, "recent"), + (1, "newest"), + (2, "frequent"), + (3, "random"), + (4, "highest"), + ] { + key(&mut app, '0'); + app.table.select(Some(index)); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(matches!(&app.view,View::Albums {kind:k,offset:0} if k==kind)); + key(&mut app, '>'); + assert!(matches!(&app.view,View::Albums {kind:k,offset:100} if k==kind)); + app.back(); + assert!(matches!(app.view, View::Home)); + assert_eq!(app.table.selected(), Some(index)); + } + app.table.select(Some(6)); + app.open(); + assert!(matches!(app.view, View::Discover)); + } + #[test] + fn browse_play_and_remove_current_queue_item() { + let mut app = App::for_tests(); + app.table.select(Some(1)); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + app.items = vec![Item::Album { + id: "album-1".into(), + name: "Test album".into(), + artist: "Test artist".into(), + cover_art: None, + }]; + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(matches!(app.view, View::Album(_))); + app.items = vec![Item::Song(crate::test_support::songs().remove(0))]; + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.current, Some(0)); + key(&mut app, '8'); + key(&mut app, 'x'); + assert!(app.queue.is_empty()); + assert_eq!(app.current, None); + key(&mut app, 'j'); + assert_eq!(app.table.selected(), Some(0)); + } + #[test] + fn queue_reordering_preserves_current_song() { + let mut app = App::for_tests(); + key(&mut app, '3'); + app.items = crate::test_support::songs() + .into_iter() + .map(Item::Song) + .collect(); + key(&mut app, 'A'); + key(&mut app, '8'); + app.play(1); + let id = app.queue[1].id.clone(); + app.table.select(Some(1)); + key(&mut app, 'J'); + assert_eq!(app.current, Some(2)); + assert_eq!(app.queue[2].id, id); + key(&mut app, 's'); + assert_eq!(app.queue[2].id, id); + } + #[test] + fn old_navigation_response_cannot_replace_new_view() { + let mut app = App::for_tests(); + let (tx, rx) = mpsc::channel(); + app.rx = rx; + let stale = app.generation; + key(&mut app, '6'); + tx.send(Reply::Loaded( + app.generation, + Ok(crate::test_support::songs() + .into_iter() + .map(Item::Song) + .collect()), + )) + .unwrap(); + tx.send(Reply::Loaded(stale, Ok(vec![]))).unwrap(); + app.tick(); + assert!(!app.items.is_empty()); + assert!(matches!(app.view, View::Discover)); + tx.send(Reply::Loaded( + app.generation, + Err(anyhow::anyhow!("Offline")), + )) + .unwrap(); + app.tick(); + assert_eq!(app.status, "Offline"); + assert!(!app.loading); + } + #[test] + fn shifted_vim_keys_change_tracks_without_changing_browse_selection() { + let mut app = App::for_tests(); + key(&mut app, '3'); + app.items = crate::test_support::songs() + .into_iter() + .map(Item::Song) + .collect(); + key(&mut app, 'A'); + app.play(1); + let selection = app.table.selected(); + app.key(KeyEvent::new(KeyCode::Char('L'), KeyModifiers::SHIFT)); + assert_eq!(app.current, Some(2)); + app.key(KeyEvent::new(KeyCode::Char('H'), KeyModifiers::SHIFT)); + assert_eq!(app.current, Some(1)); + assert_eq!(app.table.selected(), selection); + key(&mut app, 'n'); + key(&mut app, 'p'); + assert_eq!(app.current, Some(1)); + } + #[test] + fn queue_cursor_follows_playback_until_user_browses_elsewhere() { + let mut app = App::for_tests(); + app.queue = crate::test_support::songs(); + app.play(4); + key(&mut app, '8'); + assert_eq!(app.table.selected(), Some(4)); + key(&mut app, 'L'); + assert_eq!(app.table.selected(), Some(5)); + key(&mut app, 'k'); + key(&mut app, 'L'); + assert_eq!(app.current, Some(6)); + assert_eq!(app.table.selected(), Some(4)); + } + #[test] + fn repeat_and_end_of_queue_are_explicit() { + let mut app = App::for_tests(); + key(&mut app, '3'); + app.items = crate::test_support::songs() + .into_iter() + .map(Item::Song) + .collect(); + key(&mut app, 'A'); + app.play(app.queue.len() - 1); + app.next(1); + assert!(app.current.is_none()); + app.repeat = true; + app.play(app.queue.len() - 1); + app.next(1); + assert_eq!(app.current, Some(0)); + key(&mut app, ' '); + assert!(app.paused); + } + #[test] + fn download_shortcut_requests_external_song_only() { + let mut app = App::for_tests(); + let (tx, rx) = mpsc::channel(); + app.tx = tx; + // Use local view data so this test never connects to a server. + app.items = crate::test_support::songs() + .into_iter() + .map(Item::Song) + .collect(); + app.table.select(Some(0)); + key(&mut app, 'd'); + assert_eq!(app.status, "Already in library"); + assert!(rx.try_recv().is_err()); + app.table.select(Some(4)); + key(&mut app, 'd'); + match rx.try_recv().unwrap() { + Job::Star(song, true) => assert_eq!(song.id, "track-4"), + _ => panic!("Expected acquisition request"), + } + app.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)); + assert!(rx.try_recv().is_err()); + } + #[test] + fn download_request_progress_completion_and_duplicate_keys() { + let mut app = App::for_tests(); + let (jobs_tx, jobs_rx) = mpsc::channel(); + app.tx = jobs_tx; + let (reply_tx, reply_rx) = mpsc::channel(); + app.rx = reply_rx; + let song = crate::test_support::songs().remove(4); + app.items = vec![Item::Song(song.clone())]; + key(&mut app, 'd'); + assert_eq!(app.downloads[&song.id].phase, Phase::Requesting); + assert!(matches!(jobs_rx.try_recv().unwrap(), Job::Star(_, true))); + key(&mut app, '+'); + assert!(jobs_rx.try_recv().is_err()); + reply_tx + .send(Reply::Starred(Box::new(song.clone()), true, Ok(()))) + .unwrap(); + app.tick(); + assert_eq!(app.downloads[&song.id].phase, Phase::Requested); + assert!(matches!(jobs_rx.try_recv().unwrap(), Job::Acquisitions)); + reply_tx + .send(Reply::Acquisitions(Ok(Some(vec![Acquisition { + id: song.id.clone(), + state: "downloading".into(), + progress: Some(0.42), + source: Some("Soulseek".into()), + ..Default::default() + }])))) + .unwrap(); + app.tick(); + assert_eq!(app.downloads[&song.id].label(), "↓ 42%"); + app.queue = vec![song.clone()]; + key(&mut app, '8'); + assert!(app.downloads[&song.id].detail().contains("Soulseek")); + reply_tx + .send(Reply::Acquisitions(Ok(Some(vec![Acquisition { + id: song.id.clone(), + state: "done".into(), + ..Default::default() + }])))) + .unwrap(); + app.tick(); + assert_eq!(app.downloads[&song.id].phase, Phase::Done); + assert!(matches!( + jobs_rx.try_recv().unwrap(), + Job::ResolveLibrary(_, _) + )); + reply_tx + .send(Reply::LibraryResolved( + song.id.clone(), + Ok(Some(Box::new(Song { + id: "library-track".into(), + title: song.title.clone(), + ..Default::default() + }))), + )) + .unwrap(); + app.tick(); + key(&mut app, 'd'); + assert!(jobs_rx.try_recv().is_err()); + } + #[test] + fn download_failures_can_retry_and_unsupported_status_stays_requested() { + let mut app = App::for_tests(); + let song = crate::test_support::songs().remove(4); + let (jobs_tx, jobs_rx) = mpsc::channel(); + app.tx = jobs_tx; + let (reply_tx, reply_rx) = mpsc::channel(); + app.rx = reply_rx; + app.items = vec![Item::Song(song.clone())]; + key(&mut app, '+'); + let _ = jobs_rx.recv().unwrap(); + reply_tx + .send(Reply::Starred( + Box::new(song.clone()), + true, + Err(anyhow::anyhow!("Rejected")), + )) + .unwrap(); + app.tick(); + assert_eq!(app.downloads[&song.id].phase, Phase::Failed); + key(&mut app, 'd'); + assert!(matches!(jobs_rx.try_recv().unwrap(), Job::Star(_, true))); + reply_tx + .send(Reply::Starred(Box::new(song.clone()), true, Ok(()))) + .unwrap(); + app.tick(); + let _ = jobs_rx.recv().unwrap(); + reply_tx.send(Reply::Acquisitions(Ok(None))).unwrap(); + app.tick(); + assert_eq!(app.downloads[&song.id].phase, Phase::Requested); + assert!( + app.downloads[&song.id] + .detail() + .contains("server status unavailable") + ); + assert!(!app.downloads[&song.id].pollable()); + } + #[test] + fn library_copy_updates_queue_duplicates_history_and_late_results_without_restarting_audio() { + let mut app = App::for_tests(); + let remote = crate::test_support::songs().remove(4); + let directory = + std::env::temp_dir().join(format!("octo-queue-test-{:x}", rand::random::<u64>())); + app.session_path = Some(directory.join("session.json")); + app.listening_history = vec![remote.clone()]; + app.queue = vec![remote.clone(), remote.clone()]; + app.current = Some(0); + app.position = 12.; + app.view = View::Queue; + app.items = app.queue.iter().cloned().map(Item::Song).collect(); + app.back_stack.push(( + View::Songs { offset: 0 }, + vec![Item::Song(remote.clone())], + 0, + false, + )); + let commands = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + app.player = Some(Box::new(crate::test_support::TestPlayback { + commands: commands.clone(), + ..Default::default() + })); + let (job_tx, job_rx) = mpsc::channel(); + app.tx = job_tx; + let (reply_tx, reply_rx) = mpsc::channel(); + app.rx = reply_rx; + reply_tx + .send(Reply::Acquisitions(Ok(Some(vec![Acquisition { + id: remote.id.clone(), + state: "done".into(), + library_id: Some("library-42".into()), + ..Default::default() + }])))) + .unwrap(); + app.tick(); + assert!( + matches!(job_rx.try_recv().unwrap(),Job::ResolveLibrary(source,id) if source==remote.id && id=="library-42") + ); + assert!(app.queue[0].is_external); + reply_tx + .send(Reply::LibraryResolved(remote.id.clone(), Ok(None))) + .unwrap(); + app.tick(); + assert!(app.queue[0].is_external); + assert!(!app.downloads[&remote.id].library_resolved); + let library = Song { + id: "library-42".into(), + title: remote.title.clone(), + album: "Local album".into(), + ..Default::default() + }; + reply_tx + .send(Reply::LibraryResolved( + remote.id.clone(), + Ok(Some(Box::new(library))), + )) + .unwrap(); + app.tick(); + assert!( + app.queue + .iter() + .all(|s| s.id == "library-42" && !s.is_external) + ); + assert_eq!(app.items[0].playback_source(), "Library"); + assert_eq!(app.back_stack[0].1[0].playback_source(), "Library"); + assert_eq!(app.listening_history[0].id, "library-42"); + assert!(!app.listening_history[0].is_external); + assert_eq!(app.current, Some(0)); + assert_eq!(app.position, 12.); + assert!(commands.lock().unwrap().is_empty()); + reply_tx + .send(Reply::Loaded(app.generation, Ok(vec![Item::Song(remote)]))) + .unwrap(); + app.tick(); + assert_eq!(app.items[0].playback_source(), "Library"); + let saved: Session = + serde_json::from_slice(&std::fs::read(directory.join("session.json")).unwrap()) + .unwrap(); + assert!( + saved + .queue + .iter() + .all(|song| song.id == "library-42" && !song.is_external) + ); + std::fs::remove_dir_all(directory).unwrap(); + app.play(1); + let messages = commands.lock().unwrap(); + let url = reqwest::Url::parse(messages[0][1].as_str().unwrap()).unwrap(); + assert!( + url.query_pairs() + .any(|(key, value)| key == "id" && value == "library-42") + ); + } + #[test] + fn playlist_submission_waits_for_indexing_and_sends_library_id_only() { + let mut app = App::for_tests(); + let remote = crate::test_support::songs().remove(4); + app.items = vec![Item::Song(remote.clone())]; + app.queue = vec![remote.clone()]; + let mut download = Download::requesting(); + download.update(&Acquisition { + state: "done".into(), + library_id: Some("local-song".into()), + ..Default::default() + }); + app.downloads.insert(remote.id.clone(), download); + app.next_acquisition_poll = Instant::now() + Duration::from_secs(60); + let (job_tx, job_rx) = mpsc::channel(); + app.tx = job_tx; + let (reply_tx, reply_rx) = mpsc::channel(); + app.rx = reply_rx; + key(&mut app, 'a'); + let Job::PlaylistChoices(dialog_id) = job_rx.recv().unwrap() else { + unreachable!() + }; + reply_tx + .send(Reply::PlaylistChoices( + dialog_id, + Ok(vec![PlaylistChoice { + id: "playlist".into(), + name: "Evening".into(), + ..Default::default() + }]), + )) + .unwrap(); + app.tick(); + assert!(matches!(job_rx.recv().unwrap(),Job::ResolveLibrary(_,id) if id=="local-song")); + key(&mut app, 'j'); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!( + app.playlist_dialog + .as_ref() + .unwrap() + .pending_target + .is_some() + ); + assert!(job_rx.try_recv().is_err()); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(job_rx.try_recv().is_err()); + reply_tx + .send(Reply::LibraryResolved( + remote.id.clone(), + Ok(Some(Box::new(Song { + id: "local-song".into(), + title: remote.title, + ..Default::default() + }))), + )) + .unwrap(); + app.tick(); + assert!( + matches!(job_rx.recv().unwrap(),Job::PlaylistAdd(id,_,song) if id==dialog_id && song=="local-song") + ); + assert_eq!(app.queue[0].id, "local-song"); + assert!(!app.queue[0].is_external); + } + #[test] + fn cancelling_index_wait_never_submits_the_playlist_change() { + let mut app = App::for_tests(); + let remote = crate::test_support::songs().remove(4); + app.items = vec![Item::Song(remote.clone())]; + let (job_tx, job_rx) = mpsc::channel(); + app.tx = job_tx; + let (reply_tx, reply_rx) = mpsc::channel(); + app.rx = reply_rx; + key(&mut app, 'a'); + let _ = job_rx.recv().unwrap(); + let mut download = Download::requesting(); + download.phase = Phase::Done; + download.resolve_pending = true; + app.downloads.insert(remote.id.clone(), download); + key(&mut app, 'n'); + for c in "New list".chars() { + key(&mut app, c); + } + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!( + app.playlist_dialog + .as_ref() + .unwrap() + .pending_target + .is_some() + ); + app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + assert!(app.playlist_dialog.is_none()); + reply_tx + .send(Reply::LibraryResolved( + remote.id, + Ok(Some(Box::new(Song { + id: "local-song".into(), + ..Default::default() + }))), + )) + .unwrap(); + app.tick(); + assert!(job_rx.try_recv().is_err()); + } + #[test] + fn readonly_playlist_stays_visible_but_normal_playlist_can_be_added_to() { + let mut app = App::for_tests(); + app.items = vec![Item::Song(crate::test_support::songs().remove(0))]; + let (job_tx, job_rx) = mpsc::channel(); + app.tx = job_tx; + let (reply_tx, reply_rx) = mpsc::channel(); + app.rx = reply_rx; + key(&mut app, 'a'); + let Job::PlaylistChoices(id) = job_rx.recv().unwrap() else { + unreachable!() + }; + reply_tx + .send(Reply::PlaylistChoices( + id, + Ok(vec![ + PlaylistChoice { + id: "station".into(), + name: "Station".into(), + readonly: true, + ..Default::default() + }, + PlaylistChoice { + id: "mine".into(), + name: "My playlist".into(), + readonly: false, + ..Default::default() + }, + ]), + )) + .unwrap(); + app.tick(); + assert_eq!(app.playlist_dialog.as_ref().unwrap().choices.len(), 2); + key(&mut app, 'j'); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(job_rx.try_recv().is_err()); + assert!( + app.playlist_dialog + .as_ref() + .unwrap() + .error + .as_deref() + .unwrap() + .contains("read-only") + ); + key(&mut app, 'j'); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!( + matches!(job_rx.recv().unwrap(),Job::PlaylistAdd(_,PlaylistTarget::Existing {id,..},_) if id=="mine") + ); + } + #[test] + fn playlist_picker_appends_captured_song_and_preserves_queue() { + let mut app = App::for_tests(); + app.view = View::Songs { offset: 0 }; + app.items = crate::test_support::songs() + .into_iter() + .map(Item::Song) + .collect(); + let (job_tx, job_rx) = mpsc::channel(); + app.tx = job_tx; + let (reply_tx, reply_rx) = mpsc::channel(); + app.rx = reply_rx; + key(&mut app, 'a'); + assert!(app.queue.is_empty()); + let Job::PlaylistChoices(id) = job_rx.try_recv().unwrap() else { + panic!("Expected playlist list request") + }; + reply_tx + .send(Reply::PlaylistChoices( + id, + Ok(vec![PlaylistChoice { + id: "list-1".into(), + name: "Evening".into(), + readonly: false, + ..Default::default() + }]), + )) + .unwrap(); + app.tick(); + key(&mut app, 'j'); + assert_eq!(app.table.selected(), Some(0)); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + let Job::PlaylistAdd(request, target, song) = job_rx.try_recv().unwrap() else { + panic!("Expected playlist append") + }; + assert_eq!(song, "track-0"); + assert!(matches!(&target,PlaylistTarget::Existing {id,..} if id=="list-1")); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(job_rx.try_recv().is_err()); + reply_tx + .send(Reply::PlaylistAdded( + request, + target.clone(), + Err(anyhow::anyhow!("Permission denied")), + )) + .unwrap(); + app.tick(); + assert!( + app.playlist_dialog + .as_ref() + .unwrap() + .error + .as_deref() + .unwrap() + .contains("Permission denied") + ); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(matches!( + job_rx.try_recv().unwrap(), + Job::PlaylistAdd(_, _, _) + )); + reply_tx + .send(Reply::PlaylistAdded(request, target, Ok(()))) + .unwrap(); + app.tick(); + assert!(app.playlist_dialog.is_none()); + assert!(app.status.contains("Evening")); + assert!(app.queue.is_empty()); + key(&mut app, 'e'); + assert_eq!(app.queue[0].id, "track-0"); + } + #[test] + fn new_playlist_name_is_text_input_and_blank_names_do_not_submit() { + let mut app = App::for_tests(); + app.items = vec![Item::Song(crate::test_support::songs().remove(0))]; + let (job_tx, job_rx) = mpsc::channel(); + app.tx = job_tx; + let (reply_tx, reply_rx) = mpsc::channel(); + app.rx = reply_rx; + key(&mut app, 'a'); + let _ = job_rx.recv().unwrap(); + key(&mut app, 'n'); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(job_rx.try_recv().is_err()); + assert!(app.playlist_dialog.as_ref().unwrap().error.is_some()); + for c in " Café j/k ".chars() { + key(&mut app, c); + } + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + let Job::PlaylistAdd(id, target, song) = job_rx.try_recv().unwrap() else { + panic!("Expected create with song") + }; + assert!(matches!(&target,PlaylistTarget::New {name} if name=="Café j/k")); + assert_eq!(song, "track-0"); + reply_tx + .send(Reply::PlaylistAdded(id, target, Ok(()))) + .unwrap(); + app.tick(); + assert!(app.playlist_dialog.is_none()); + } + #[test] + fn closing_picker_discards_late_list_results() { + let mut app = App::for_tests(); + app.items = vec![Item::Song(crate::test_support::songs().remove(0))]; + let (job_tx, job_rx) = mpsc::channel(); + app.tx = job_tx; + let (reply_tx, reply_rx) = mpsc::channel(); + app.rx = reply_rx; + key(&mut app, 'a'); + let Job::PlaylistChoices(old) = job_rx.recv().unwrap() else { + unreachable!() + }; + app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + assert!(app.playlist_dialog.is_none()); + key(&mut app, 'a'); + let Job::PlaylistChoices(new) = job_rx.recv().unwrap() else { + unreachable!() + }; + assert_ne!(old, new); + reply_tx + .send(Reply::PlaylistChoices( + old, + Ok(vec![PlaylistChoice { + id: "old".into(), + ..Default::default() + }]), + )) + .unwrap(); + app.tick(); + assert!(app.playlist_dialog.as_ref().unwrap().choices.is_empty()); + assert!(app.playlist_dialog.as_ref().unwrap().loading); + } + #[test] + fn now_playing_reports_confirmed_library_tracks_once_per_start() { + use PlayerEvent::{Error, Loaded, Paused, Position}; + + let mut app = App::for_tests(); + let (reports, tracks) = mpsc::channel(); + app.now_playing = Some(reports); + app.queue = crate::test_support::songs(); + app.queue[1].is_external = true; + let player = crate::test_support::TestPlayback::default(); + let events = player.events.clone(); + app.player = Some(Box::new(player)); + let tick = |app: &mut App, playback_events: Vec<PlayerEvent>, expected: &[&str]| { + events.lock().unwrap().extend(playback_events); + app.tick(); + assert_eq!(tracks.try_iter().collect::<Vec<_>>(), expected); + }; + + app.play(0); + tick(&mut app, vec![Position(1.)], &[]); + tick(&mut app, vec![Loaded, Position(0.)], &[]); + tick(&mut app, vec![Paused(true), Position(0.5)], &[]); + tick( + &mut app, + vec![Paused(false), Position(1.), Position(2.)], + &["track-0"], + ); + + app.play(1); + tick(&mut app, vec![Loaded, Position(1.)], &[]); + app.play(2); + tick( + &mut app, + vec![Error("Stream failed".into()), Position(1.)], + &[], + ); + app.play(2); + tick(&mut app, vec![Loaded, Position(1.)], &["track-2"]); + app.play(0); + tick(&mut app, vec![Loaded, Position(1.)], &["track-0"]); + } + #[test] + fn now_playing_failure_is_visible_only_for_the_current_track() { + let mut app = App::for_tests(); + let (replies, rx) = mpsc::channel(); + app.rx = rx; + app.queue = crate::test_support::songs(); + app.play(1); + let report_failure = |id: &str| { + replies + .send(Reply::NowPlayingFailed( + id.into(), + anyhow::anyhow!("scrobble: HTTP 503"), + )) + .unwrap(); + }; + + report_failure("track-0"); + let status = app.status.clone(); + app.tick(); + assert_eq!(app.status, status); + + report_failure("track-1"); + app.tick(); + assert_eq!(app.status, "Now Playing report failed (scrobble: HTTP 503)"); + assert_eq!(app.current, Some(1)); + } + #[test] + fn listening_history_records_confirmed_playback_and_survives_restarts() { + let mut app = App::for_tests(); + app.queue = crate::test_support::songs(); + let directory = + std::env::temp_dir().join(format!("octo-listening-test-{:x}", rand::random::<u64>())); + let path = directory.join("session.json"); + app.session_path = Some(path.clone()); + let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + app.player = Some(Box::new(crate::test_support::TestPlayback { + events: events.clone(), + ..Default::default() + })); + app.play(0); + events.lock().unwrap().push(PlayerEvent::Position(1.)); + app.tick(); + assert!(app.listening_history.is_empty()); + events + .lock() + .unwrap() + .extend([PlayerEvent::Loaded, PlayerEvent::Position(0.)]); + app.tick(); + assert!(app.listening_history.is_empty()); + events.lock().unwrap().push(PlayerEvent::Position(0.5)); + app.tick(); + assert_eq!(app.listening_history[0].id, "track-0"); + app.play(1); + events.lock().unwrap().extend([ + PlayerEvent::Error("Stream failed".into()), + PlayerEvent::Position(1.), + ]); + app.tick(); + assert_eq!(app.listening_history.len(), 1); + for index in [2, 0] { + app.play(index); + events + .lock() + .unwrap() + .extend([PlayerEvent::Loaded, PlayerEvent::Position(1.)]); + app.tick(); + } + assert_eq!( + app.listening_history + .iter() + .map(|s| s.id.as_str()) + .collect::<Vec<_>>(), + ["track-0", "track-2"] + ); + let (tx, jobs) = mpsc::channel(); + let (_reply, rx) = mpsc::channel(); + let mut restored = App::with_channels(app.api.clone(), 70, Some(path), tx, rx); + key(&mut restored, '9'); + assert!(matches!(restored.view, View::History)); + assert_eq!(restored.items[0].title(), "Track 0"); + restored.queue.clear(); + key(&mut restored, 'a'); + assert!(matches!(jobs.try_recv().unwrap(), Job::PlaylistChoices(_))); + assert_eq!( + restored.playlist_dialog.as_ref().unwrap().song.id, + "track-0" + ); + std::fs::remove_dir_all(directory).unwrap(); + } + #[test] + fn listening_history_is_bounded_and_keeps_selection_while_new_tracks_arrive() { + let mut app = App::for_tests(); + app.listening_history = (0..1000) + .map(|n| Song { + id: n.to_string(), + title: format!("Track {n}"), + ..Default::default() + }) + .collect(); + key(&mut app, '9'); + app.table.select(Some(10)); + app.record_play(Song { + id: "new".into(), + title: "New track".into(), + ..Default::default() + }); + assert_eq!(app.listening_history.len(), 1000); + assert_eq!(app.items[0].title(), "New track"); + assert_eq!(app.selected_song().unwrap().id, "10"); + assert!(!app.listening_history.iter().any(|s| s.id == "999")); + app.record_play(Song { + id: "10".into(), + title: "Track 10".into(), + ..Default::default() + }); + assert_eq!(app.listening_history[0].id, "10"); + assert_eq!( + app.listening_history + .iter() + .filter(|s| s.id == "10") + .count(), + 1 + ); + assert_eq!(app.table.selected(), Some(0)); + } + #[test] + fn theme_shortcut_and_old_sessions_remain_compatible() { + let mut app = App::for_tests(); + key(&mut app, 't'); + assert_eq!(app.theme, Theme::Nord); + let saved = serde_json::to_vec(&Session { + library_only: false, + theme: app.theme, + volume: 70, + queue: crate::test_support::songs(), + listening_history: vec![], + }) + .unwrap(); + let restored: Session = serde_json::from_slice(&saved).unwrap(); + assert_eq!(restored.theme, Theme::Nord); + assert_eq!( + restored.queue[4].octo_suggested_by.as_deref(), + Some("Last.fm") + ); + assert_eq!( + serde_json::from_str::<Session>(r#"{"queue":[],"volume":70}"#) + .unwrap() + .theme, + Theme::Spotifyish + ); + } + #[test] + fn view_search_moves_to_first_match_without_filtering_or_server_jobs() { + let mut app = App::for_tests(); + app.view = View::Queue; + app.queue = vec![ + Song { + id: "a".into(), + title: "Opening".into(), + artist: "Björk".into(), + ..Default::default() + }, + Song { + id: "b".into(), + title: "Café".into(), + album: "Evening".into(), + ..Default::default() + }, + Song { + id: "c".into(), + title: "Café reprise".into(), + ..Default::default() + }, + ]; + app.refresh_queue(); + app.table.select(Some(2)); + let (tx, jobs) = mpsc::channel(); + app.tx = tx; + key(&mut app, '/'); + for c in "CAFÉ".chars() { + key(&mut app, c); + } + assert_eq!(app.table.selected(), Some(1)); + assert_eq!(app.items.len(), 3); + assert!(matches!(app.view, View::Queue)); + assert!(jobs.try_recv().is_err()); + key(&mut app, '!'); + assert_eq!(app.table.selected(), Some(1)); + app.key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); + assert_eq!(app.input.as_deref(), Some("CAFÉ")); + app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + assert_eq!(app.table.selected(), Some(2)); + + for query in ["BJÖRK", "evening"] { + key(&mut app, '/'); + for c in query.chars() { + key(&mut app, c); + } + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!( + app.selected_song().unwrap().id, + if query == "BJÖRK" { "a" } else { "b" } + ); + } + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.current, Some(1)); + assert_eq!(app.queue.len(), 3); + assert!(jobs.try_recv().is_err()); + } + + #[test] + fn unicode_search_and_history() { + let mut app = App::for_tests(); + let (tx, jobs) = mpsc::channel(); + app.tx = tx; + key(&mut app, '1'); + key(&mut app, 'é'); + app.key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); + assert_eq!(app.input, Some(String::new())); + for c in "radiohead".chars() { + key(&mut app, c); + } + assert!(jobs.try_recv().is_err()); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(matches!(&app.view,View::Search(query) if query=="radiohead")); + assert!( + matches!(jobs.try_recv().unwrap(), Job::Load(_, View::Search(query), _) if query == "radiohead") + ); + app.back(); + assert!(matches!(app.view, View::Home)); + } +}
A
src/artwork.rs
@@ -0,0 +1,316 @@
+use crate::api::Api; +use anyhow::{Context, Result, bail}; +use image::{DynamicImage, ImageReader, Rgba}; +use ratatui_image::protocol::{ImageSource, StatefulProtocol, sixel::StatefulSixel}; +use std::{ + collections::VecDeque, + io::{Cursor, Read, Write}, + sync::{ + Arc, + mpsc::{self, Receiver, Sender}, + }, + time::{Duration, Instant}, +}; + +#[derive(Default)] +pub struct Artwork { + pub enabled: bool, + pub protocol: Option<StatefulProtocol>, + pub message: String, + pub title: String, + target: Option<String>, + image_size: Option<(u32, u32)>, + font_size: (u16, u16), + background: [u8; 4], + cache: VecDeque<(String, DynamicImage)>, + tx: Option<Sender<String>>, + rx: Option<Receiver<(String, Result<DynamicImage>)>>, +} + +impl Artwork { + /// Coalesce playback changes on a dedicated worker so covers cannot block music requests. + pub fn new(api: Arc<Api>, font_size: (u16, u16)) -> Self { + let (tx, jobs) = mpsc::channel::<String>(); + let (results, rx) = mpsc::channel(); + std::thread::spawn(move || { + while let Ok(mut id) = jobs.recv() { + for newer in jobs.try_iter() { + id = newer; + } + let result = api.cover_art(&id); + if results.send((id, result)).is_err() { + break; + } + } + }); + Self { + enabled: true, + font_size, + background: [16, 20, 28, 255], + tx: Some(tx), + rx: Some(rx), + ..Self::default() + } + } + /// Cache decoded images and discard stale results when the playing track changes. + pub fn update(&mut self, cover: Option<(String, String)>) { + if !self.enabled { + return; + } + let (id, title) = cover.map_or((None, String::new()), |(id, title)| (Some(id), title)); + self.title = title; + if id != self.target { + self.target = id.clone(); + self.protocol = None; + self.image_size = None; + self.message = if id.is_some() { + "Loading cover…" + } else { + "No cover available" + } + .into(); + if let Some(id) = id { + if let Some(index) = self.cache.iter().position(|(key, _)| key == &id) { + let entry = self.cache.remove(index).unwrap(); + self.show(entry.1.clone()); + self.cache.push_back(entry); + } else if let Some(tx) = &self.tx { + let _ = tx.send(id); + } + } + } + let replies: Vec<_> = self + .rx + .as_ref() + .map(|rx| rx.try_iter().collect()) + .unwrap_or_default(); + for (id, result) in replies { + match result { + Ok(image) => { + if self.target.as_ref() == Some(&id) { + self.show(image.clone()); + } + self.cache.retain(|(key, _)| key != &id); + self.cache.push_back((id, image)); + while self.cache.len() > 8 { + self.cache.pop_front(); + } + } + Err(e) if self.target.as_ref() == Some(&id) => self.message = e.to_string(), + _ => {} + } + } + } + /// Rebuild the cached protocol when a theme changes the image's letterbox color. + pub fn set_background(&mut self, color: ratatui::style::Color) { + if let ratatui::style::Color::Rgb(r, g, b) = color { + let background = [r, g, b, 255]; + if self.background != background { + self.background = background; + let image = self + .cache + .iter() + .find(|(id, _)| self.target.as_ref() == Some(id)) + .map(|(_, image)| image.clone()); + if let Some(image) = image { + self.show(image); + } + } + } + } + /// Fit the cover to its column without reserving unused rows below the image. + pub fn height_for_width(&self, width: u16, max_height: u16) -> u16 { + let (image_width, image_height) = self.image_size.unwrap_or((1, 1)); + let (cell_width, cell_height) = if self.font_size.0 > 0 && self.font_size.1 > 0 { + self.font_size + } else { + (8, 16) + }; + let pixels = u64::from(width) * u64::from(cell_width) * u64::from(image_height); + let rows = pixels.div_ceil(u64::from(image_width.max(1)) * u64::from(cell_height)); + rows.min(u64::from(max_height)) as u16 + } + fn show(&mut self, image: DynamicImage) { + self.image_size = Some((image.width(), image.height())); + let source = ImageSource::new(image, self.font_size, Rgba(self.background)); + self.protocol = Some(StatefulProtocol::Sixel(StatefulSixel::new( + source, + self.font_size, + std::env::var_os("TMUX").is_some(), + ))); + self.message.clear(); + } +} + +/// Bound decoded allocations as well as compressed downloads. +pub fn decode(bytes: &[u8]) -> Result<DynamicImage> { + let mut reader = ImageReader::new(Cursor::new(bytes)) + .with_guessed_format() + .context("Unknown cover format")?; + let mut limits = image::Limits::default(); + limits.max_image_width = Some(4096); + limits.max_image_height = Some(4096); + limits.max_alloc = Some(64 * 1024 * 1024); + reader.limits(limits); + let image = reader.decode().context("Cannot decode cover")?; + if image.width() == 0 || image.height() == 0 { + bail!("Empty cover"); + } + Ok(image.thumbnail(image.width().min(320), image.height().min(320))) +} + +/// Query SIXEL support with a bounded poll; never leave a background stdin reader behind. +pub fn terminal_font_size() -> Option<(u16, u16)> { + let fallback = crossterm::terminal::window_size() + .ok() + .filter(|s| s.columns > 0 && s.rows > 0 && s.width >= s.columns && s.height >= s.rows) + .map(|s| (s.width / s.columns, s.height / s.rows)) + .unwrap_or((8, 16)); + let mut stdout = std::io::stdout(); + if stdout + .write_all(b"\x1b[c\x1b[16t") + .and_then(|_| stdout.flush()) + .is_err() + { + return None; + } + let mut stdin = std::io::stdin(); + let deadline = Instant::now() + Duration::from_millis(250); + let mut response = Vec::new(); + while Instant::now() < deadline && response.len() < 1024 { + let mut fds = [rustix::event::PollFd::new( + &stdin, + rustix::event::PollFlags::IN, + )]; + let timeout = deadline + .saturating_duration_since(Instant::now()) + .as_millis() as i32; + if rustix::event::poll(&mut fds, timeout).ok()? == 0 { + break; + } + let mut bytes = [0; 128]; + let n = stdin.read(&mut bytes).ok()?; + if n == 0 { + break; + } + response.extend_from_slice(&bytes[..n]); + } + let response = String::from_utf8_lossy(&response); + query_response(&response, fallback) +} + +fn query_response(response: &str, fallback: (u16, u16)) -> Option<(u16, u16)> { + let supported = response.split("\x1b[?").skip(1).any(|s| { + s.split_once('c') + .is_some_and(|(params, _)| params.split(';').any(|p| p == "4")) + }); + if !supported { + return None; + } + let font = response.split("\x1b[6;").skip(1).find_map(|s| { + let (params, _) = s.split_once('t')?; + let (height, width) = params.split_once(';')?; + let (w, h) = (width.parse::<u16>().ok()?, height.parse::<u16>().ok()?); + (w > 0 && h > 0 && w <= 256 && h <= 256).then_some((w, h)) + }); + Some(font.unwrap_or(fallback)) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn capabilities_require_sixel_and_nonzero_cells() { + assert_eq!( + query_response("\x1b[?62;4;22c\x1b[6;20;10t", (8, 16)), + Some((10, 20)) + ); + assert_eq!( + query_response("\x1b[?62;4c\x1b[6;0;0t", (8, 16)), + Some((8, 16)) + ); + assert_eq!(query_response("\x1b[?62;24c", (8, 16)), None); + assert_eq!(query_response("", (8, 16)), None); + } + #[test] + fn old_cover_does_not_replace_current_track() { + let (tx, rx) = mpsc::channel(); + let mut art = Artwork { + enabled: true, + font_size: (8, 16), + rx: Some(rx), + ..Default::default() + }; + art.update(Some(("new".into(), "New".into()))); + tx.send(("old".into(), Ok(DynamicImage::new_rgb8(96, 96)))) + .unwrap(); + art.update(Some(("new".into(), "New".into()))); + assert!(art.protocol.is_none()); + tx.send(("new".into(), Ok(DynamicImage::new_rgb8(96, 96)))) + .unwrap(); + art.update(Some(("new".into(), "New".into()))); + assert!(art.protocol.is_some()); + art.update(Some(("old".into(), "Old".into()))); + assert!(art.protocol.is_some()); + art.update(None); + assert!(art.protocol.is_none()); + } + #[test] + fn cover_height_tracks_aspect_ratio_cell_size_and_available_space() { + let mut art = Artwork { + font_size: (8, 16), + ..Default::default() + }; + art.show(DynamicImage::new_rgb8(200, 200)); + assert_eq!(art.height_for_width(26, 100), 13); + assert_eq!(art.height_for_width(26, 6), 6); + art.show(DynamicImage::new_rgb8(400, 200)); + assert_eq!(art.height_for_width(26, 100), 7); + art.show(DynamicImage::new_rgb8(200, 400)); + assert_eq!(art.height_for_width(26, 100), 26); + assert_eq!(art.height_for_width(26, 0), 0); + assert_eq!(art.height_for_width(0, 100), 0); + } + + #[test] + fn rendering_emits_sixel_and_resizes_after_theme_change() { + use ratatui::{buffer::Buffer, layout::Rect, widgets::StatefulWidget}; + let mut art = Artwork { + enabled: true, + font_size: (8, 16), + ..Default::default() + }; + art.show(DynamicImage::new_rgb8(96, 96)); + for (width, height) in [(24, 12), (12, 6)] { + let area = Rect::new(0, 0, width, height); + let mut buffer = Buffer::empty(area); + ratatui_image::StatefulImage::default().render( + area, + &mut buffer, + art.protocol.as_mut().unwrap(), + ); + assert!( + buffer + .content + .iter() + .any(|c| c.symbol().starts_with("\x1bP")) + ); + } + art.set_background(crate::theme::Theme::Monokai.palette().bg); + assert_eq!(art.background, [39, 40, 34, 255]); + } + #[test] + fn decoding_rejects_non_images_and_excessive_dimensions() { + assert!(decode(b"not an image").is_err()); + let mut png = Cursor::new(Vec::new()); + DynamicImage::new_rgb8(4097, 1) + .write_to(&mut png, image::ImageFormat::Png) + .unwrap(); + assert!(decode(png.get_ref()).is_err()); + let mut png = Cursor::new(Vec::new()); + DynamicImage::new_rgb8(96, 96) + .write_to(&mut png, image::ImageFormat::Png) + .unwrap(); + assert_eq!(decode(png.get_ref()).unwrap().width(), 96); + } +}
A
src/config.rs
@@ -0,0 +1,53 @@
+use anyhow::{Result, bail}; +use serde::Deserialize; +use std::{env, path::PathBuf}; + +#[derive(Default, Deserialize)] +#[serde(default)] +pub struct Config { + pub server: String, + pub username: String, + pub password: String, + pub api_key: String, + pub volume: Option<u8>, + pub theme: Option<String>, +} + +pub fn directory() -> PathBuf { + env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env::var_os("HOME").unwrap_or_default()).join(".config")) + .join("octo-tui") +} + +impl Config { + /// Environment overrides keep credentials out of command-line arguments. + pub fn load(path: Option<PathBuf>) -> Result<Self> { + let explicit = path.is_some(); + let path = path.unwrap_or_else(|| directory().join("config.toml")); + let mut config: Self = match std::fs::read_to_string(&path) { + Ok(text) => { + toml::from_str(&text).map_err(|_| anyhow::anyhow!("Invalid configuration TOML"))? + } + Err(e) if !explicit && e.kind() == std::io::ErrorKind::NotFound => Self::default(), + Err(_) => bail!("Cannot read configuration file"), + }; + for (name, field) in [ + ("OCTO_SERVER", &mut config.server), + ("OCTO_USERNAME", &mut config.username), + ("OCTO_PASSWORD", &mut config.password), + ("OCTO_API_KEY", &mut config.api_key), + ] { + if let Ok(value) = env::var(name) { + *field = value; + } + } + if config.server.is_empty() { + bail!("Set OCTO_SERVER or configure server in ~/.config/octo-tui/config.toml."); + } + if config.api_key.is_empty() && (config.username.is_empty() || config.password.is_empty()) { + bail!("Set OCTO_USERNAME and OCTO_PASSWORD, or OCTO_API_KEY."); + } + Ok(config) + } +}
A
src/downloads.rs
@@ -0,0 +1,170 @@
+use serde::Deserialize; +use std::time::Instant; + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Acquisition { + pub id: String, + pub state: String, + pub progress: Option<f64>, + pub bytes_done: Option<u64>, + pub bytes_total: Option<u64>, + pub source: Option<String>, + pub started_at: Option<String>, + pub library_id: Option<String>, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Phase { + Requesting, + Requested, + Queued, + Searching, + Downloading, + Verifying, + Importing, + Done, + Failed, + Unknown, +} + +pub struct Download { + pub phase: Phase, + progress: Option<f64>, + source: Option<String>, + pub unavailable: bool, + pub last_seen: Instant, + pub library_id: Option<String>, + pub library_resolved: bool, + pub resolve_pending: bool, + pub next_resolve: Instant, +} + +impl Download { + pub fn requesting() -> Self { + Self { + phase: Phase::Requesting, + progress: None, + source: None, + unavailable: false, + last_seen: Instant::now(), + library_id: None, + library_resolved: false, + resolve_pending: false, + next_resolve: Instant::now(), + } + } + pub fn in_flight(&self) -> bool { + !matches!(self.phase, Phase::Done | Phase::Failed) + } + pub fn pollable(&self) -> bool { + ((self.in_flight() && self.phase != Phase::Requesting) + || (self.phase == Phase::Done && !self.library_resolved)) + && !self.unavailable + } + /// Keep server progress distinct from the client's request acknowledgement. + pub fn update(&mut self, acquisition: &Acquisition) { + self.phase = match acquisition.state.as_str() { + "queued" => Phase::Queued, + "searching" => Phase::Searching, + "downloading" => Phase::Downloading, + "verifying" => Phase::Verifying, + "importing" => Phase::Importing, + "done" => Phase::Done, + "failed" => Phase::Failed, + _ => Phase::Unknown, + }; + self.progress = acquisition + .progress + .filter(|p| p.is_finite()) + .map(|p| p.clamp(0., 1.)) + .or_else(|| { + acquisition + .bytes_done + .zip(acquisition.bytes_total) + .filter(|(_, total)| *total > 0) + .map(|(done, total)| (done as f64 / total as f64).clamp(0., 1.)) + }); + self.source = acquisition.source.clone().filter(|s| !s.trim().is_empty()); + if let Some(id) = acquisition + .library_id + .clone() + .filter(|id| !id.trim().is_empty()) + { + self.library_id = Some(id); + } + self.unavailable = false; + self.last_seen = Instant::now(); + } + pub fn label(&self) -> String { + match self.phase { + Phase::Requesting => "REQUEST".into(), + Phase::Requested => "REQUESTED".into(), + Phase::Queued => "QUEUED".into(), + Phase::Searching => "SEARCHING".into(), + Phase::Downloading => self + .progress + .map(|p| format!("↓ {:.0}%", p * 100.)) + .unwrap_or_else(|| "↓ FETCH".into()), + Phase::Verifying => "VERIFYING".into(), + Phase::Importing => "IMPORTING".into(), + Phase::Done => "✓ ADDED".into(), + Phase::Failed => "FAILED".into(), + Phase::Unknown => "WAITING".into(), + } + } + pub fn detail(&self) -> String { + let mut detail = self.label(); + if let Some(source) = &self.source { + detail.push_str(&format!(" · {source}")); + } + if self.phase == Phase::Done && !self.library_resolved { + detail.push_str(" · waiting for library metadata"); + } + if self.unavailable { + detail.push_str(" · server status unavailable"); + } + detail + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn unknown_server_stage_keeps_polling_until_completion() { + let mut download = Download::requesting(); + download.update(&Acquisition { + state: "future-stage".into(), + ..Default::default() + }); + assert!(download.pollable()); + assert_eq!(download.label(), "WAITING"); + download.update(&Acquisition { + state: "failed".into(), + ..Default::default() + }); + assert!(!download.pollable()); + } + #[test] + fn server_progress_uses_bytes_when_fraction_is_missing() { + let mut download = Download::requesting(); + download.update(&Acquisition { + state: "downloading".into(), + bytes_done: Some(50), + bytes_total: Some(200), + source: Some("Soulseek".into()), + ..Default::default() + }); + assert_eq!(download.label(), "↓ 25%"); + assert!(download.detail().contains("Soulseek")); + download.update(&Acquisition { + state: "done".into(), + ..Default::default() + }); + assert!(download.pollable()); + download.library_resolved = true; + assert!(!download.pollable()); + assert_eq!(download.label(), "✓ ADDED"); + } +}
A
src/main.rs
@@ -0,0 +1,86 @@
+mod api; +mod app; +mod artwork; +mod config; +mod downloads; +mod model; +mod player; +mod playlists; +#[cfg(test)] +mod test_support; +mod theme; +mod ui; + +use anyhow::{Result, bail}; +use crossterm::event::{self, Event, KeyEventKind}; +use std::{path::PathBuf, sync::Arc, time::Duration}; + +fn main() -> Result<()> { + let mut no_art = false; + let mut theme = None; + let mut config_path = None; + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + match arg.as_str() { + "--no-art" => no_art = true, + "--theme" => { + theme = Some( + args.next() + .ok_or_else(|| anyhow::anyhow!("--theme needs a name"))? + .parse::<theme::Theme>()?, + ) + } + "--config" => { + config_path = Some(PathBuf::from( + args.next() + .ok_or_else(|| anyhow::anyhow!("--config needs a path"))?, + )) + } + "--help" | "-h" => { + println!( + "octo-tui [--config PATH] [--theme NAME] [--no-art]\n\nVim-friendly Octo / Subsonic music player. Playback requires mpv.\n\nConfigure ~/.config/octo-tui/config.toml or set:\n OCTO_SERVER, OCTO_USERNAME, OCTO_PASSWORD (or OCTO_API_KEY)\n\nThemes: dark, monokai, spotifyish (default), nord, gruvbox, daylight, paper. Press t to cycle.\nCovers: SIXEL detected automatically; --no-art disables it.\nPress ? in the TUI for shortcuts." + ); + return Ok(()); + } + "--version" | "-V" => { + println!("octo-tui {}", env!("CARGO_PKG_VERSION")); + return Ok(()); + } + _ => bail!("Unknown argument. Use --help for usage."), + } + } + let config = config::Config::load(config_path)?; + let volume = config.volume.unwrap_or(70); + let configured_theme = config + .theme + .as_deref() + .map(str::parse::<theme::Theme>) + .transpose()?; + let api = Arc::new(api::Api::new(config)?); + let mut app = app::App::new(api.clone(), volume); + if let Some(theme) = theme.or(configured_theme) { + app.theme = theme; + } + let mut terminal = ratatui::init(); + if !no_art && let Some(font_size) = artwork::terminal_font_size() { + app.artwork = artwork::Artwork::new(api, font_size); + } + let result = run(&mut terminal, &mut app); + ratatui::restore(); + app.save(); + result +} + +fn run(terminal: &mut ratatui::DefaultTerminal, app: &mut app::App) -> Result<()> { + while !app.quit { + app.tick(); + terminal.draw(|frame| ui::draw(frame, app))?; + if event::poll(Duration::from_millis(100))? + && let Event::Key(key) = event::read()? + && key.kind != KeyEventKind::Release + { + app.key(key); + } + } + Ok(()) +}
A
src/model.rs
@@ -0,0 +1,253 @@
+use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Song { + pub id: String, + pub title: String, + pub artist: String, + pub artist_id: Option<String>, + pub album: String, + pub album_id: Option<String>, + pub cover_art: Option<String>, + pub duration: u64, + pub year: Option<u32>, + pub starred: Option<String>, + pub is_external: bool, + pub octo_suggested_by: Option<String>, + // A documented server default, not the recommendation or catalog provider. + pub playback_source: Option<String>, +} + +#[derive(Clone, Debug)] +pub enum Item { + HomeSection(HomeSection), + Song(Song), + Album { + id: String, + name: String, + artist: String, + cover_art: Option<String>, + }, + Artist { + id: String, + name: String, + }, + Playlist { + id: String, + name: String, + }, + Genre(String), + Station { + id: String, + name: String, + }, +} + +impl Item { + pub fn title(&self) -> &str { + match self { + Self::HomeSection(section) => section.title(), + Self::Song(s) => &s.title, + Self::Album { name, .. } + | Self::Artist { name, .. } + | Self::Playlist { name, .. } + | Self::Station { name, .. } => name, + Self::Genre(name) => name, + } + } + /// Prefer the server's explicit cover key, including for external discoveries. + pub fn cover(&self) -> Option<(String, String)> { + match self { + Self::Song(s) => Some(( + s.cover_art + .as_ref() + .or(s.album_id.as_ref()) + .unwrap_or(&s.id) + .clone(), + s.title.clone(), + )), + Self::Album { + id, + name, + cover_art, + .. + } => Some((cover_art.as_ref().unwrap_or(id).clone(), name.clone())), + _ => None, + } + } + pub fn playback_source(&self) -> &str { + match self { + Self::Song(s) if !s.is_external => "Library", + Self::Song(s) => s.playback_source.as_deref().unwrap_or("Unknown"), + _ => "—", + } + } + pub fn recommendation_source(&self) -> &str { + match self { + Self::Song(s) => s + .octo_suggested_by + .as_deref() + .filter(|s| !s.trim().is_empty()) + .unwrap_or(if s.is_external { "Unknown" } else { "—" }), + _ => "—", + } + } + pub fn detail(&self) -> String { + match self { + Self::HomeSection(section) => section.description().into(), + Self::Song(s) => format!("{} · {}", s.artist, s.album), + Self::Album { artist, .. } => artist.clone(), + Self::Artist { .. } => "Artist → tracks".into(), + Self::Playlist { .. } => "Playlist → tracks".into(), + Self::Station { .. } => "Octo station → tracks".into(), + Self::Genre(_) => "Genre → tracks".into(), + } + } + pub fn label(&self) -> &str { + match self { + Self::HomeSection(_) => "BROWSE", + Self::Song(s) if s.is_external => "DISCOVER", + Self::Song(s) if s.starred.is_some() => "♥", + Self::Song(_) => "LIBRARY", + Self::Album { .. } => "ALBUM", + Self::Artist { .. } => "ARTIST", + Self::Playlist { .. } => "LIST", + Self::Genre(_) => "GENRE", + Self::Station { .. } => "STATION", + } + } +} + +#[derive(Clone, Debug)] +pub enum View { + Home, + Albums { kind: String, offset: usize }, + Artists, + Songs { offset: usize }, + History, + Playlists, + Genres, + Discover, + Stations, + Search(String), + Album(String), + Artist(String), + ArtistByName(String), + Playlist(String), + Genre(String), + Radio(String), + Station(String), + Queue, +} + +impl View { + pub fn title(&self) -> String { + match self { + Self::Albums { kind, offset } => format!( + "Albums · {} · page {}", + album_order_title(kind), + offset / 100 + 1 + ), + Self::Songs { offset } => format!("Songs · page {}", offset / 100 + 1), + Self::Search(q) => format!("Search · {q}"), + Self::Album(_) => "Album tracks".into(), + Self::Artist(_) => "Artist tracks".into(), + Self::ArtistByName(name) => format!("Artist tracks · {name}"), + Self::Playlist(_) => "Playlist tracks".into(), + Self::Genre(g) => format!("Genre · {g}"), + Self::Radio(_) => "Song radio · similar tracks".into(), + Self::Station(_) => "Station tracks".into(), + other => format!("{other:?}"), + } + } +} + +#[derive(Clone, Copy, Debug)] +pub enum HomeSection { + RecentlyPlayed, + RecentlyAdded, + MostPlayed, + Rediscover, + HighestRated, + History, + Discover, + Stations, +} + +impl HomeSection { + pub const ALL: [Self; 8] = [ + Self::RecentlyPlayed, + Self::RecentlyAdded, + Self::MostPlayed, + Self::Rediscover, + Self::HighestRated, + Self::History, + Self::Discover, + Self::Stations, + ]; + pub fn title(self) -> &'static str { + match self { + Self::RecentlyPlayed => "Recently played", + Self::RecentlyAdded => "Recently added", + Self::MostPlayed => "Most played", + Self::Rediscover => "Rediscover", + Self::HighestRated => "Highest rated", + Self::History => "History", + Self::Discover => "Discover new music", + Self::Stations => "Stations", + } + } + pub fn description(self) -> &'static str { + match self { + Self::RecentlyPlayed => "Albums you listened to most recently", + Self::RecentlyAdded => "The newest additions to your library", + Self::MostPlayed => "Your most frequently played albums", + Self::Rediscover => "A random selection from your library", + Self::HighestRated => "Albums with the highest server ratings", + Self::History => "Songs played in this player, newest first", + Self::Discover => "Octo charts or a library shuffle", + Self::Stations => "Explore your server's Octo stations", + } + } + /// Reuse paginated album browsing and existing discovery views for each shelf. + pub fn view(self) -> View { + let kind = match self { + Self::RecentlyPlayed => "recent", + Self::RecentlyAdded => "newest", + Self::MostPlayed => "frequent", + Self::Rediscover => "random", + Self::HighestRated => "highest", + Self::History => return View::History, + Self::Discover => return View::Discover, + Self::Stations => return View::Stations, + }; + View::Albums { + kind: kind.into(), + offset: 0, + } + } +} + +/// Home is available immediately, even while the server is offline. +pub fn home_items() -> Vec<Item> { + HomeSection::ALL + .into_iter() + .map(Item::HomeSection) + .collect() +} + +fn album_order_title(kind: &str) -> &str { + match kind { + "recent" => "Recently played", + "newest" => "Recently added", + "frequent" => "Most played", + "random" => "Rediscover", + "highest" => "Highest rated", + other => other, + } +} + +pub fn time(seconds: u64) -> String { + format!("{}:{:02}", seconds / 60, seconds % 60) +}
A
src/player.rs
@@ -0,0 +1,213 @@
+use anyhow::{Context, Result, bail}; +use serde_json::{Value, json}; +use std::{ + fs, + io::{BufRead, BufReader, Write}, + os::unix::{fs::DirBuilderExt, net::UnixStream}, + path::PathBuf, + process::{Child, Command, Stdio}, + sync::mpsc::{self, Receiver}, + time::{Duration, Instant}, +}; + +#[derive(Debug)] +pub enum PlayerEvent { + Loaded, + Position(f64), + Duration(f64), + Paused(bool), + Finished, + Error(String), +} +/// Keep the mpv transport boundary replaceable in tests without an audio device. +pub trait Playback { + fn command(&mut self, command: Value) -> Result<()>; + fn drain_events(&self) -> Vec<PlayerEvent>; +} +pub struct Player { + child: Child, + socket: UnixStream, + directory: PathBuf, + pub events: Receiver<PlayerEvent>, +} + +impl Player { + /// A private IPC directory keeps stream authentication out of process arguments. + pub fn start(volume: u8) -> Result<Self> { + let directory = std::env::temp_dir().join(format!( + "octo-tui-{}-{:x}", + std::process::id(), + rand::random::<u64>() + )); + fs::DirBuilder::new().mode(0o700).create(&directory)?; + let path = directory.join("mpv.sock"); + let spawned = Command::new("mpv") + .args([ + "--idle=yes", + "--no-video", + "--no-terminal", + "--audio-display=no", + "--input-terminal=no", + ]) + .arg(format!("--volume={volume}")) + .arg(format!("--input-ipc-server={}", path.display())) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn(); + let mut child = match spawned { + Ok(child) => child, + Err(_) => { + let _ = fs::remove_dir_all(&directory); + bail!("Install mpv to enable playback; browsing remains available"); + } + }; + let deadline = Instant::now() + Duration::from_secs(3); + let socket = loop { + if let Ok(socket) = UnixStream::connect(&path) { + break socket; + } + if Instant::now() > deadline || child.try_wait()?.is_some() { + let _ = child.kill(); + let _ = child.wait(); + let _ = fs::remove_dir_all(&directory); + bail!("mpv could not start its playback socket"); + } + std::thread::sleep(Duration::from_millis(20)); + }; + socket.set_write_timeout(Some(Duration::from_millis(200)))?; + let reader = BufReader::new(socket.try_clone()?); + let (tx, events) = mpsc::channel(); + std::thread::spawn(move || { + for line in reader.lines() { + let Ok(line) = line else { break }; + let Ok(v) = serde_json::from_str::<Value>(&line) else { + continue; + }; + let event = player_event(&v); + if let Some(event) = event + && tx.send(event).is_err() + { + break; + } + } + }); + let mut player = Self { + child, + socket, + directory, + events, + }; + for (id, property) in ["time-pos", "duration", "pause"].iter().enumerate() { + player.command(json!(["observe_property", id, property]))?; + } + Ok(player) + } + pub fn command(&mut self, command: Value) -> Result<()> { + let mut request = json!({"command":command}); + if request["command"][0] == "loadfile" { + request["request_id"] = json!(1); + } + let message = serde_json::to_string(&request)?; + writeln!(self.socket, "{message}").context("Cannot communicate with mpv") + } +} +/// Use structured mpv errors only; never echo logs or URLs that can contain authentication. +fn player_event(v: &Value) -> Option<PlayerEvent> { + if v["request_id"] == 1 && v["error"].as_str().is_some_and(|error| error != "success") { + return Some(PlayerEvent::Error( + "Playback failed: mpv rejected the loadfile command. Check the installed mpv version." + .into(), + )); + } + match v["event"].as_str() { + Some("file-loaded") => Some(PlayerEvent::Loaded), + Some("property-change") => match v["name"].as_str() { + Some("time-pos") => v["data"].as_f64().map(PlayerEvent::Position), + Some("duration") => v["data"].as_f64().map(PlayerEvent::Duration), + Some("pause") => v["data"].as_bool().map(PlayerEvent::Paused), + _ => None, + }, + Some("end-file") if v["reason"] == "eof" => Some(PlayerEvent::Finished), + Some("end-file") if v["reason"] == "error" => { + let reason = match v["file_error"].as_str().or_else(|| v["error"].as_str()) { + Some("audio output initialization failed") => { + "mpv cannot initialize audio output. Check its configured audio device." + } + Some("loading failed") | Some("error opening file") => { + "mpv could not open the server stream. Check HTTP/TLS access, authentication, and song availability." + } + Some("unrecognized file format") => { + "the server response is not a supported audio stream; it may be a sign-in page or server error." + } + Some("audio decoder initialization failed") | Some("decoding failed") => { + "mpv could not decode the audio stream." + } + Some("no audio or video data played") => "the stream contained no playable audio.", + _ => "mpv reported an unknown stream/output error.", + }; + Some(PlayerEvent::Error(format!("Playback failed: {reason}"))) + } + _ => None, + } +} + +impl Playback for Player { + fn command(&mut self, command: Value) -> Result<()> { + Player::command(self, command) + } + fn drain_events(&self) -> Vec<PlayerEvent> { + self.events.try_iter().collect() + } +} +impl Drop for Player { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + let _ = fs::remove_dir_all(&self.directory); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn playback_failures_distinguish_stream_format_and_audio_output() { + for (error, expected) in [ + ("loading failed", "could not open the server stream"), + ("unrecognized file format", "not a supported audio stream"), + ( + "audio output initialization failed", + "cannot initialize audio output", + ), + ] { + let event = + player_event(&json!({"event":"end-file","reason":"error","file_error":error})); + assert!( + matches!(event, Some(PlayerEvent::Error(message)) if message.contains(expected)) + ); + } + } + + #[test] + fn errors_never_echo_unknown_server_text_or_signed_urls() { + let secret = "https://example.invalid/stream?apiKey=private"; + for reply in [ + json!({"event":"end-file","reason":"error","file_error":secret}), + json!({"request_id":1,"error":secret}), + ] { + let Some(PlayerEvent::Error(message)) = player_event(&reply) else { + panic!("missing error") + }; + assert!(!message.contains(secret)); + assert!(!message.contains("private")); + } + assert!(player_event(&json!({"request_id":1,"error":"success"})).is_none()); + assert!(matches!( + player_event(&json!({"event":"end-file","reason":"eof"})), + Some(PlayerEvent::Finished) + )); + assert!(player_event(&json!({"event":"end-file","reason":"stop"})).is_none()); + } +}
A
src/playlists.rs
@@ -0,0 +1,163 @@
+use crate::model::Song; +use serde_json::Value; + +#[derive(Clone, Debug, Default)] +pub struct PlaylistChoice { + pub id: String, + pub name: String, + pub readonly: bool, + pub upkeep: bool, + pub imported: bool, + pub upkeep_kind: Option<String>, +} + +impl PlaylistChoice { + /// Upkeep action lists can alter files; the playlist picker only adds to music or request lists. + pub fn addition_error(&self) -> Option<&'static str> { + if self.readonly || self.imported { + Some( + "The server marks this playlist read-only. Choose another or create a new playlist.", + ) + } else if self.upkeep && self.upkeep_kind.as_deref() != Some("request") { + Some( + "Library upkeep action and notice lists cannot be used by the add-to-playlist dialog.", + ) + } else { + None + } + } + pub fn suffix(&self) -> &'static str { + if self.readonly || self.imported { + " [read-only]" + } else if self.upkeep { + " [library upkeep]" + } else { + "" + } + } +} +fn wire_bool(value: &Value) -> bool { + match value { + Value::Bool(value) => *value, + Value::String(value) => value.eq_ignore_ascii_case("true") || value == "1", + Value::Number(value) => value.as_u64() == Some(1), + _ => false, + } +} + +/// Share parsing between the browse section and picker; optional metadata must not hide a list. +pub fn parse_playlist_choices(value: &Value) -> Vec<PlaylistChoice> { + let Some(rows) = value.as_array() else { + return vec![]; + }; + rows.iter() + .filter_map(|row| { + let id = match &row["id"] { + Value::String(id) => id.clone(), + Value::Number(id) if id.is_i64() || id.is_u64() => id.to_string(), + _ => return None, + }; + if id.trim().is_empty() { + return None; + } + let name = row["name"] + .as_str() + .filter(|name| !name.trim().is_empty()) + .unwrap_or(&id) + .to_owned(); + let readonly = match row.get("readonly").or_else(|| row.get("readOnly")) { + Some(Value::Bool(value)) => *value, + Some(Value::String(value)) => value.eq_ignore_ascii_case("true") || value == "1", + Some(Value::Number(value)) => value.as_u64() == Some(1), + _ => false, + }; + Some(PlaylistChoice { + id, + name, + readonly, + upkeep: wire_bool(&row["octoUpkeep"]), + imported: wire_bool(&row["octoImport"]), + upkeep_kind: row["octoUpkeepKind"].as_str().map(str::to_owned), + }) + }) + .collect() +} + +#[derive(Clone, Debug)] +pub enum PlaylistTarget { + Existing { id: String, name: String }, + New { name: String }, +} +impl PlaylistTarget { + pub fn name(&self) -> &str { + match self { + Self::Existing { name, .. } | Self::New { name } => name, + } + } +} + +pub struct PlaylistDialog { + pub id: u64, + pub song: Song, + pub choices: Vec<PlaylistChoice>, + pub selected: usize, + pub loading: bool, + pub saving: bool, + pub new_name: Option<String>, + pub error: Option<String>, + pub pending_target: Option<PlaylistTarget>, +} +impl PlaylistDialog { + pub fn new(id: u64, song: Song) -> Self { + Self { + id, + song, + choices: vec![], + selected: 0, + loading: true, + saving: false, + new_name: None, + error: None, + pending_target: None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn upkeep_actions_and_imports_cannot_be_used_as_normal_playlists() { + let choices = parse_playlist_choices(&serde_json::json!([ + {"id":"normal"}, + {"id":"action","octoUpkeep":true,"octoUpkeepKind":"action"}, + {"id":"notice","octoUpkeep":true,"octoUpkeepKind":"notice"}, + {"id":"old-action","octoUpkeep":true}, + {"id":"request","octoUpkeep":true,"octoUpkeepKind":"request"}, + {"id":"import","octoImport":true} + ])); + assert!(choices[0].addition_error().is_none()); + for i in [1, 2, 3, 5] { + assert!(choices[i].addition_error().is_some()); + } + assert!(choices[4].addition_error().is_none()); + } + #[test] + fn optional_metadata_and_one_bad_row_do_not_hide_playlists() { + let rows = serde_json::json!([ + {"id":"mine","name":"My songs","readonly":null,"owner":null}, + {"id":42,"name":"Numeric ID","readonly":"false"}, + {"id":"generated","name":"Station","readonly":true}, + {"id":"other","name":"Chart","readOnly":"true"}, + {"id":null,"name":"Invalid"}, + {"id":"unnamed","name":null} + ]); + let choices = parse_playlist_choices(&rows); + assert_eq!(choices.len(), 5); + assert!(!choices[0].readonly); + assert_eq!(choices[1].id, "42"); + assert!(choices[2].readonly); + assert!(choices[3].readonly); + assert_eq!(choices[4].name, "unnamed"); + } +}
A
src/test_support.rs
@@ -0,0 +1,35 @@
+//! Fixtures and audio-transport doubles compiled only by the test harness. +use crate::{ + model::Song, + player::{Playback, PlayerEvent}, +}; + +pub fn songs() -> Vec<Song> { + (0..8) + .map(|index| Song { + id: format!("track-{index}"), + title: format!("Track {index}"), + artist: "Test artist".into(), + album: "Test album".into(), + duration: 240, + is_external: index >= 4, + octo_suggested_by: (index >= 4).then(|| "Last.fm".into()), + ..Default::default() + }) + .collect() +} + +#[derive(Default)] +pub struct TestPlayback { + pub events: std::sync::Arc<std::sync::Mutex<Vec<PlayerEvent>>>, + pub commands: std::sync::Arc<std::sync::Mutex<Vec<serde_json::Value>>>, +} +impl Playback for TestPlayback { + fn command(&mut self, command: serde_json::Value) -> anyhow::Result<()> { + self.commands.lock().unwrap().push(command); + Ok(()) + } + fn drain_events(&self) -> Vec<PlayerEvent> { + self.events.lock().unwrap().drain(..).collect() + } +}
A
src/theme.rs
@@ -0,0 +1,168 @@
+use anyhow::{Result, bail}; +use ratatui::style::Color; +use serde::{Deserialize, Serialize}; +use std::str::FromStr; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum Theme { + Dark, + Monokai, + #[default] + Spotifyish, + Nord, + Gruvbox, + Daylight, + Paper, +} + +pub struct Palette { + pub bg: Color, + pub panel: Color, + pub accent: Color, + pub muted: Color, + pub text: Color, + pub selection: Color, + pub border: Color, +} + +impl Theme { + pub fn name(self) -> &'static str { + match self { + Self::Dark => "dark", + Self::Monokai => "monokai", + Self::Spotifyish => "spotifyish", + Self::Nord => "nord", + Self::Gruvbox => "gruvbox", + Self::Daylight => "daylight", + Self::Paper => "paper", + } + } + pub fn next(self) -> Self { + match self { + Self::Dark => Self::Monokai, + Self::Monokai => Self::Spotifyish, + Self::Spotifyish => Self::Nord, + Self::Nord => Self::Gruvbox, + Self::Gruvbox => Self::Daylight, + Self::Daylight => Self::Paper, + Self::Paper => Self::Dark, + } + } + /// Shared semantic colors keep all widgets consistent when switching themes. + pub fn palette(self) -> Palette { + let (bg, panel, accent, muted, text, selection) = match self { + Self::Dark => (0x10141c, 0x171d28, 0x64dcc2, 0x909bb1, 0xe0e7f1, 0x263a46), + Self::Monokai => (0x272822, 0x34352f, 0xf92672, 0xa6a28c, 0xf8f8f2, 0x49483e), + Self::Spotifyish => (0x121212, 0x202020, 0x1ed760, 0xb3b3b3, 0xffffff, 0x303d34), + Self::Nord => (0x2e3440, 0x3b4252, 0x88c0d0, 0xa4b0c3, 0xeceff4, 0x4c566a), + Self::Gruvbox => (0x282828, 0x3c3836, 0xfabd2f, 0xbdae93, 0xebdbb2, 0x504945), + Self::Daylight => (0xffffff, 0xeef2f6, 0x004899, 0x384555, 0x111827, 0xdbe8ff), + Self::Paper => (0xfff8e8, 0xf3ead4, 0x733510, 0x504538, 0x251e16, 0xe5d6b7), + }; + let rgb = |hex: u32| Color::Rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8); + Palette { + bg: rgb(bg), + panel: rgb(panel), + accent: rgb(accent), + muted: rgb(muted), + text: rgb(text), + selection: rgb(selection), + border: rgb(match self { + Self::Daylight => 0x526070, + Self::Paper => 0x6b5c48, + Self::Gruvbox => 0x665c54, + _ => panel, + }), + } + } +} +impl FromStr for Theme { + type Err = anyhow::Error; + fn from_str(value: &str) -> Result<Self> { + match value.to_ascii_lowercase().as_str() { + "dark" => Ok(Self::Dark), + "monokai" => Ok(Self::Monokai), + "spotifyish" => Ok(Self::Spotifyish), + "nord" => Ok(Self::Nord), + "gruvbox" => Ok(Self::Gruvbox), + "daylight" => Ok(Self::Daylight), + "paper" => Ok(Self::Paper), + _ => { + bail!( + "Unknown theme. Choose dark, monokai, spotifyish, nord, gruvbox, daylight, or paper." + ) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn theme_cycle_includes_light_themes_and_roundtrips_settings() { + let mut theme = Theme::default(); + let mut names = std::collections::HashSet::new(); + loop { + assert!(names.insert(theme.name())); + assert_eq!(theme.name().parse::<Theme>().unwrap(), theme); + assert_eq!( + serde_json::from_str::<Theme>(&serde_json::to_string(&theme).unwrap()).unwrap(), + theme + ); + theme = theme.next(); + if theme == Theme::default() { + break; + } + } + assert!(names.contains("gruvbox")); + assert!(names.contains("daylight")); + assert!(names.contains("paper")); + } + #[test] + fn outdoor_themes_keep_text_keys_and_borders_readable() { + let luminance = |color: Color| { + let Color::Rgb(r, g, b) = color else { + panic!("Expected RGB") + }; + let linear = |value: u8| { + let v = f64::from(value) / 255.; + if v <= 0.04045 { + v / 12.92 + } else { + ((v + 0.055) / 1.055).powf(2.4) + } + }; + 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b) + }; + let contrast = |a, b| { + let (a, b) = (luminance(a), luminance(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) + }; + for theme in [Theme::Daylight, Theme::Paper] { + let palette = theme.palette(); + for background in [palette.bg, palette.panel, palette.selection] { + for foreground in [palette.text, palette.accent, palette.muted] { + assert!( + contrast(foreground, background) >= 4.5, + "{} has low text contrast", + theme.name() + ); + } + } + assert!(contrast(palette.border, palette.bg) >= 3.); + } + } + #[test] + fn only_current_theme_name_is_accepted() { + let theme: Theme = serde_json::from_str("\"spotifyish\"").unwrap(); + assert_eq!("spotifyish".parse::<Theme>().unwrap(), theme); + assert_eq!(serde_json::to_string(&theme).unwrap(), "\"spotifyish\""); + for removed in ["spotify", "spotify-ish"] { + assert!(removed.parse::<Theme>().is_err()); + assert!(serde_json::from_str::<Theme>(&format!("\"{removed}\"")).is_err()); + } + } +}
A
src/ui.rs
@@ -0,0 +1,1380 @@
+use crate::{ + app::{App, NAV}, + model::{Item, time}, +}; +use ratatui::{ + Frame, + layout::{Constraint, Direction, Layout, Rect}, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{ + Block, Borders, Clear, Gauge, List, ListItem, ListState, Paragraph, Row, Table, Wrap, + }, +}; + +/// Keep the browser and transport visible, with a compact layout for narrow terminals. +pub fn draw(frame: &mut Frame, app: &mut App) { + let area = frame.area(); + let colors = app.theme.palette(); + frame.render_widget( + Block::default().style(Style::default().bg(colors.bg).fg(colors.text)), + area, + ); + if area.width < 45 || area.height < 14 { + frame.render_widget( + Paragraph::new("Octo · enlarge terminal to at least 45 × 14\nq quits") + .wrap(Wrap { trim: false }), + area, + ); + return; + } + let selected_download = app + .items + .get(app.table.selected().unwrap_or(0)) + .and_then(|item| match item { + Item::Song(song) => app.downloads.get(&song.id), + _ => None, + }) + .map(|download| download.detail()); + let rows = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Length(3), + Constraint::Min(4), + Constraint::Length(4), + Constraint::Length( + (if area.width < 100 { 4 } else { 3 }) + u16::from(selected_download.is_some()), + ), + ]) + .split(area); + let mode = if app.library_only { + "LIBRARY ONLY · m toggles" + } else { + "SUBSONIC / OCTO · m library only" + }; + frame.render_widget( + Paragraph::new(Line::from(vec![ + Span::styled( + " ◉ OCTO ", + Style::default() + .fg(colors.accent) + .add_modifier(Modifier::BOLD), + ), + Span::styled( + " / terminal listening room", + Style::default().fg(colors.muted), + ), + Span::raw(format!(" {mode}")), + ])) + .block( + Block::default() + .borders(Borders::BOTTOM) + .border_style(Style::default().fg(colors.border)), + ), + rows[0], + ); + let show_cover = app.artwork.enabled + && area.width >= 100 + && area.height >= 20 + && (!matches!(app.view, crate::model::View::Home) || app.current.is_some()); + let show_queue = + area.width >= 100 && area.height >= 20 && (show_cover || !app.queue.is_empty()); + let cols = Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Length(if area.width < 75 { 16 } else { 23 }), + Constraint::Min(20), + Constraint::Length(if show_queue { 28 } else { 0 }), + ]) + .split(rows[1]); + let nav: Vec<_> = NAV + .iter() + .enumerate() + .map(|(i, name)| { + let active = i == app.nav; + let style = if active { + Style::default() + .fg(colors.accent) + .bg(colors.panel) + .add_modifier(Modifier::BOLD) + } else { + Style::default().fg(colors.muted) + }; + ListItem::new(format!( + " {} {} {}", + if active { "›" } else { " " }, + i, + name + )) + .style(style) + }) + .collect(); + let mut nav_state = ListState::default().with_selected(Some(app.nav)); + frame.render_stateful_widget( + List::new(nav).block( + Block::default() + .title(if app.sidebar { + " Browse ● " + } else { + " Browse " + }) + .borders(Borders::ALL) + .border_style(Style::default().fg(if app.sidebar { + colors.accent + } else { + colors.border + })), + ), + cols[0], + &mut nav_state, + ); + let block = Block::default() + .title(format!(" {} · {} ", app.view.title(), app.items.len())) + .borders(Borders::ALL) + .border_style(Style::default().fg(if app.sidebar { + colors.border + } else { + colors.accent + })); + if app.items.is_empty() { + let message = if let Some(error) = &app.load_error { + format!("Could not load {}:\n{error}\nR retries", app.view.title()) + } else if matches!(app.view, crate::model::View::History) && !app.library_only { + "No listening history yet.\nSongs appear after playback starts.".into() + } else if app.loading { + "Loading music…\nYou can keep browsing or press q to quit.".into() + } else if matches!(app.view, crate::model::View::Playlists) { + "No playlists returned for this account.\nSelect a song and press a to create one.\nR refreshes".into() + } else if app.library_only { + "No library songs in this view.\nm includes online songs · R refreshes".into() + } else if matches!( + app.view, + crate::model::View::Stations | crate::model::View::Station(_) + ) { + "No station tracks returned.\nOcto station tracks require the octoStations extension.\nR refreshes".into() + } else { + "No results.\n1 server search · 6 discover · R refresh".into() + }; + frame.render_widget( + Paragraph::new(message) + .style(Style::default().fg(colors.muted)) + .wrap(Wrap { trim: false }) + .block(block), + cols[1], + ); + } else if matches!(app.view, crate::model::View::Home) { + let entries = app + .items + .iter() + .map(|item| Row::new([item.title().to_owned(), item.detail()])); + let widths = [ + Constraint::Min(20), + if cols[1].width >= 55 { + Constraint::Percentage(55) + } else { + Constraint::Length(0) + }, + ]; + frame.render_stateful_widget( + Table::new(entries, widths) + .header( + Row::new(["SECTION", "BROWSE"]) + .style(Style::default().fg(colors.muted)) + .bottom_margin(1), + ) + .block(block) + .row_highlight_style( + Style::default() + .bg(colors.selection) + .add_modifier(Modifier::BOLD), + ) + .highlight_symbol("› "), + cols[1], + &mut app.table, + ); + } else { + let artist_view = matches!( + app.view, + crate::model::View::Artist(_) | crate::model::View::ArtistByName(_) + ); + let table_rows: Vec<_> = app + .items + .iter() + .enumerate() + .map(|(i, item)| { + let playing=if matches!(app.view,crate::model::View::Queue) { + app.current==Some(i) + } else { + matches!(item,Item::Song(song) if app.current.and_then(|index|app.queue.get(index)).is_some_and(|current|current.id==song.id)) + }; + let download = match item { + Item::Song(song) => app.downloads.get(&song.id), + _ => None, + }; + let title = if playing { + let progress = download + .map(|d| format!("[{}] ", d.label())) + .unwrap_or_default(); + format!( + "{} {progress}{}", + if app.paused { "Ⅱ" } else { "▶" }, + item.title() + ) + } else { + item.title().to_owned() + }; + let duration = if let Item::Song(s) = item { + time(s.duration) + } else { + String::new() + }; + Row::new(vec![ + if playing { + if app.paused { + "Ⅱ PAUSED" + } else { + "▶ PLAYING" + } + .into() + } else if let Some(download) = download { + download.label() + } else { + item.label().to_owned() + }, + title, + if artist_view { + match item { Item::Song(song) => song.album.clone(), _ => item.detail() } + } else { + item.detail() + }, + item.recommendation_source().to_owned(), + item.playback_source().to_owned(), + match item { + Item::Song(song) => song.year.filter(|year| *year > 0).map(|year| year.to_string()).unwrap_or_else(|| "—".into()), + _ => String::new(), + }, + duration, + ]) + .style( + Style::default() + .fg(if matches!(item,Item::Song(s) if s.is_external) { + colors.accent + } else { + colors.text + }) + .add_modifier(if playing { + Modifier::BOLD + } else { + Modifier::empty() + }), + ) + }) + .collect(); + let table_width = cols[1].width; + let source_width = if table_width >= if artist_view { 110 } else { 82 } { + 18 + } else { + 0 + }; + let show_year = + table_width >= 60 && app.items.iter().any(|item| matches!(item, Item::Song(_))); + let widths = vec![ + Constraint::Length(9), + Constraint::Min(12), + if artist_view && table_width >= 45 { + Constraint::Percentage(30) + } else if table_width >= 110 { + Constraint::Percentage(28) + } else { + Constraint::Length(0) + }, + Constraint::Length(source_width), + Constraint::Length(source_width), + Constraint::Length(if show_year { 4 } else { 0 }), + Constraint::Length(5), + ]; + frame.render_stateful_widget( + Table::new(table_rows, widths) + .header( + Row::new([ + "STATUS", + "TITLE", + if artist_view { + "ALBUM" + } else { + "ARTIST / ALBUM" + }, + "SUGGESTED BY", + "LOADED FROM", + "YEAR", + "TIME", + ]) + .style(Style::default().fg(colors.muted)) + .bottom_margin(1), + ) + .block(block) + .row_highlight_style( + Style::default() + .bg(colors.selection) + .add_modifier(Modifier::BOLD), + ) + .highlight_symbol("› "), + cols[1], + &mut app.table, + ); + } + let now = app.current.and_then(|i| app.queue.get(i)); + let side = if show_cover { + let image_height = app.artwork.height_for_width( + cols[2].width.saturating_sub(2), + cols[2].height.saturating_sub(8), + ); + Layout::vertical([Constraint::Length(image_height + 4), Constraint::Min(4)]).split(cols[2]) + } else { + Layout::vertical([Constraint::Length(0), Constraint::Min(0)]).split(cols[2]) + }; + if show_cover { + let block = Block::default() + .title(" Cover · SIXEL ") + .borders(Borders::ALL) + .border_style(Style::default().fg(colors.border)); + let inner = block.inner(side[0]); + frame.render_widget(block, side[0]); + let parts = Layout::vertical([Constraint::Min(1), Constraint::Length(2)]).split(inner); + if !app.help && app.playlist_dialog.is_none() { + if let Some(protocol) = &mut app.artwork.protocol { + frame.render_stateful_widget( + ratatui_image::StatefulImage::default().resize(ratatui_image::Resize::Scale( + Some(ratatui_image::FilterType::Triangle), + )), + parts[0], + protocol, + ); + } else { + frame.render_widget( + Paragraph::new(app.artwork.message.as_str()) + .style(Style::default().fg(colors.muted)) + .wrap(Wrap { trim: false }), + parts[0], + ); + } + } + frame.render_widget( + Paragraph::new(vec![ + Line::from(Span::styled( + app.artwork.title.as_str(), + Style::default().fg(colors.text), + )), + Line::from(Span::styled( + now.map(|song| song.artist.as_str()).unwrap_or_default(), + Style::default().fg(colors.muted), + )), + ]), + parts[1], + ); + } + if show_queue { + draw_queue(frame, app, side[1]); + } + let title = now + .map(|s| format!("{} — {}", s.title, s.artist)) + .unwrap_or_else(|| "Choose a song to start listening".into()); + let state = if app.current.is_none() { + "STOP" + } else if app.paused { + "PAUSE" + } else { + "PLAY" + }; + let player = Block::default() + .title(format!(" {state} · {title} ")) + .borders(Borders::ALL) + .border_style(Style::default().fg(colors.border)); + let inside = player.inner(rows[2]); + frame.render_widget(player, rows[2]); + let playback = Layout::default() + .direction(Direction::Vertical) + .constraints([Constraint::Length(1), Constraint::Length(1)]) + .split(inside); + let ratio = if app.duration > 0. { + (app.position / app.duration).clamp(0., 1.) + } else { + 0. + }; + frame.render_widget( + Gauge::default() + .gauge_style(Style::default().fg(colors.accent).bg(colors.panel)) + .ratio(ratio) + .label(format!( + "{} / {}", + time(app.position as u64), + time(app.duration as u64) + )), + playback[0], + ); + let suggestion = now + .and_then(|s| s.octo_suggested_by.as_deref()) + .unwrap_or(""); + frame.render_widget( + Paragraph::new(format!( + "vol {}% · {} queued · repeat {} {} · Loaded from: {}", + app.volume, + app.queue.len(), + if app.repeat { "on" } else { "off" }, + suggestion, + now.map(|s| if s.is_external { + s.playback_source.as_deref().unwrap_or("Unknown") + } else { + "Library" + }) + .unwrap_or("—") + )) + .style(Style::default().fg(colors.muted)), + playback[1], + ); + let selected_source = app + .items + .get(app.table.selected().unwrap_or(0)) + .map(Item::recommendation_source) + .unwrap_or("—"); + let selected_playback = app + .items + .get(app.table.selected().unwrap_or(0)) + .map(Item::playback_source) + .unwrap_or("—"); + let source_line = if matches!(app.view, crate::model::View::Home) { + format!( + "0 Home · Enter opens section · theme: {} (t)", + app.theme.name() + ) + } else if area.width < 100 { + format!( + "Suggested by: {selected_source}\nLoaded from: {selected_playback} · theme: {} (t)", + app.theme.name() + ) + } else { + format!( + "Suggested by: {selected_source} · Loaded from: {selected_playback} · theme: {} (t)", + app.theme.name() + ) + }; + let source_line = if let Some(download) = selected_download { + format!("{source_line}\nDownload: {download}") + } else { + source_line + }; + let footer = if let Some(input) = &app.input { + if app.server_search { + format!("Search server: {input}▏ Enter search · Esc cancel") + } else { + format!("/ {input}▏ Find in view · Enter keep position · Esc cancel") + } + } else { + format!( + "{}\n{}\nj/k move · Enter play/open · / find · 1 server search · a playlist · e queue · r radio · d library · ? help", + app.status, source_line + ) + }; + frame.render_widget( + Paragraph::new(footer).style(Style::default().fg(if app.input.is_some() { + colors.accent + } else { + colors.muted + })), + rows[3], + ); + if app.help { + draw_help(frame, app); + } + if app.playlist_dialog.is_some() { + draw_playlist_dialog(frame, app); + } +} + +/// Keep playlist selection and naming in one modal without changing the browser's song. +fn draw_playlist_dialog(frame: &mut Frame, app: &App) { + let dialog = app.playlist_dialog.as_ref().unwrap(); + let colors = app.theme.palette(); + let area = frame.area(); + let width = area.width.saturating_sub(4).min(72); + let height = area.height.saturating_sub(2).min(22); + let popup = Rect::new( + (area.width - width) / 2, + (area.height - height) / 2, + width, + height, + ); + let block = Block::default() + .title(" Add song to playlist ") + .borders(Borders::ALL) + .border_style(Style::default().fg(colors.accent)) + .style(Style::default().fg(colors.text).bg(colors.panel)); + let inner = block.inner(popup); + frame.render_widget(Clear, popup); + frame.render_widget(block, popup); + let rows = Layout::vertical([ + Constraint::Length(3), + Constraint::Min(1), + Constraint::Length(3), + ]) + .split(inner); + frame.render_widget( + Paragraph::new(vec![ + Line::from(Span::styled( + dialog.song.title.as_str(), + Style::default().add_modifier(Modifier::BOLD), + )), + Line::from(dialog.song.artist.as_str()), + ]), + rows[0], + ); + if let Some(name) = &dialog.new_name { + frame.render_widget( + Paragraph::new(format!("New playlist name:\n{name}▏")) + .style(Style::default().fg(colors.accent)), + rows[1], + ); + } else { + let entries = std::iter::once( + ListItem::new("+ Create new playlist").style(Style::default().fg(colors.accent)), + ) + .chain(dialog.choices.iter().map(|p| { + ListItem::new(format!("{}{}", p.name, p.suffix())).style(Style::default().fg( + if p.addition_error().is_some() { + colors.muted + } else { + colors.text + }, + )) + })); + let mut state = ListState::default().with_selected(Some(dialog.selected)); + frame.render_stateful_widget( + List::new(entries).highlight_symbol("› ").highlight_style( + Style::default() + .bg(colors.selection) + .add_modifier(Modifier::BOLD), + ), + rows[1], + &mut state, + ); + } + let instructions = if dialog.pending_target.is_some() { + "Waiting for library indexing… Esc cancels" + } else if dialog.saving { + "Adding song…" + } else if dialog.new_name.is_some() { + "Enter creates and adds · Esc returns" + } else { + "j/k move · Enter adds · n new · Esc cancels" + }; + let status = dialog.error.as_deref().unwrap_or(if dialog.loading { + "Loading playlists…" + } else if dialog.choices.is_empty() { + "No existing playlists returned; n creates one" + } else { + "" + }); + frame.render_widget( + Paragraph::new(vec![ + Line::from(Span::styled(status, Style::default().fg(colors.accent))), + Line::from(instructions), + ]) + .wrap(Wrap { trim: false }), + rows[2], + ); +} + +/// Give keys their own accent color and let small terminals scroll through every binding. +fn draw_help(frame: &mut Frame, app: &mut App) { + let colors = app.theme.palette(); + let entries = [ + ("", "BROWSE"), + ("j / k · arrows", "Move selection"), + ("gg / G", "First / last entry"), + ("Ctrl-d / Ctrl-u", "Move ten rows"), + ("h / Tab", "Focus sidebar / toggle focus"), + ("l / Enter", "Open selection or play"), + ("i", "Open selected song’s artist"), + ("m", "Toggle library-only mode"), + ("Esc / Backspace", "Go back"), + ("0", "Home"), + ("2–9", "Artists through History"), + ("/", "Find in current view as you type"), + ("1", "Search the server"), + ("< / >", "Previous / next album or song page"), + ("o / R", "Cycle album order / refresh"), + ("t", "Cycle theme"), + ("", "PLAYBACK"), + ("Enter", "Play visible list from selection"), + ("Space", "Pause / resume"), + ("H / L", "Previous / next song (Shift-h/l)"), + ("[ / ]", "Seek backward / forward 10 seconds"), + ("- / =", "Volume down / up 5%"), + ("", "PLAYLISTS"), + ("a", "Add selected song to a playlist"), + ("9", "Recently played songs (History)"), + ("", "QUEUE"), + ("e / A", "Append selected / all visible songs"), + ("s", "Shuffle upcoming songs"), + ("z", "Toggle queue repeat"), + ("8", "Open full queue"), + ("x", "Remove selected queue song"), + ("J / K", "Move queue song down / up"), + ("", "DISCOVER"), + ("6 / 7", "Discover / Stations"), + ("r", "Radio from selected song"), + ("f", "Toggle favorite"), + ("d / +", "Download external song to library"), + ("", "DISCOVER labels songs not owned"), + ("? / Esc", "Close help"), + ("q / Ctrl-c", "Quit player (outside help)"), + ]; + let area = frame.area(); + let width = area.width.saturating_sub(6).min(86); + let narrow = width < 64; + let key_style = Style::default() + .fg(colors.accent) + .add_modifier(Modifier::BOLD); + let description_style = Style::default().fg(colors.text); + let mut lines = Vec::new(); + for (key, description) in entries { + if key.is_empty() { + lines.push(Line::from(Span::styled( + description, + Style::default() + .fg(colors.muted) + .add_modifier(Modifier::BOLD), + ))); + } else if narrow { + lines.push(Line::from(Span::styled(key, key_style))); + lines.push(Line::from(Span::styled( + format!(" {description}"), + description_style, + ))); + } else { + lines.push(Line::from(vec![ + Span::styled(format!("{key:<20}"), key_style), + Span::styled(description, description_style), + ])); + } + } + let height = area.height.saturating_sub(2).min(lines.len() as u16 + 2); + let popup = Rect::new( + (area.width - width) / 2, + (area.height - height) / 2, + width, + height, + ); + let block = Block::default() + .title(" Shortcuts ") + .title_bottom(Line::from(vec![ + Span::styled(" j/k · PgUp/PgDn ", key_style), + Span::styled("scroll · Esc close ", description_style), + ])) + .borders(Borders::ALL) + .border_style(Style::default().fg(colors.accent)); + let inner = block.inner(popup); + app.help_scroll = app + .help_scroll + .min((lines.len() as u16).saturating_sub(inner.height)); + frame.render_widget(Clear, popup); + frame.render_widget( + Paragraph::new(lines) + .scroll((app.help_scroll, 0)) + .style(Style::default().bg(colors.panel)) + .block(block), + popup, + ); +} + +/// Follow playback and render the live queue without moving the browser's selection. +fn draw_queue(frame: &mut Frame, app: &App, area: Rect) { + let colors = app.theme.palette(); + let block = Block::default() + .title(" Queue ") + .title_style( + Style::default() + .fg(colors.accent) + .add_modifier(Modifier::BOLD), + ) + .borders(Borders::ALL) + .border_style(Style::default().fg(colors.border)); + let inner = block.inner(area); + frame.render_widget(block, area); + if app.queue.is_empty() { + frame.render_widget( + Paragraph::new("Queue is empty\ne adds a song · 8 opens queue") + .wrap(Wrap { trim: false }) + .style(Style::default().fg(colors.muted)), + inner, + ); + return; + } + let start = app + .current + .unwrap_or(0) + .min(app.queue.len().saturating_sub(1)); + let entries = app + .queue + .iter() + .enumerate() + .skip(start) + .map(|(index, song)| { + let playing = app.current == Some(index); + let marker = if playing { + if app.paused { "Ⅱ" } else { "▶" } + } else { + "·" + }; + let download = app + .downloads + .get(&song.id) + .map(|d| format!("[{}] ", d.label())) + .unwrap_or_default(); + ListItem::new(format!("{marker} {}. {download}{}", index + 1, song.title)).style( + Style::default().fg(colors.text).add_modifier(if playing { + Modifier::BOLD + } else { + Modifier::empty() + }), + ) + }); + frame.render_widget(List::new(entries), inner); +} + +#[cfg(test)] +mod tests { + use super::*; + use ratatui::{Terminal, backend::TestBackend}; + #[test] + fn suggestion_service_remains_visible_on_narrow_terminals() { + let mut app = App::for_tests(); + app.view = crate::model::View::Discover; + app.items = vec![Item::Song(crate::model::Song { + title: "Suggested track".into(), + is_external: true, + octo_suggested_by: Some("YouTube Music".into()), + ..Default::default() + })]; + for width in [45, 80, 140] { + let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|c| c.symbol()) + .collect::<String>(); + assert!(text.contains("YouTube Music")); + } + } + #[test] + fn home_sections_and_numbered_sidebar_render() { + let mut app = App::for_tests(); + let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|c| c.symbol()) + .collect::<String>(); + for label in [ + "0 Home", + "1 Search", + "2 Artists", + "8 Queue", + "9 History", + "Recently played", + "Recently added", + "Most played", + "Highest rated", + ] { + assert!(text.contains(label), "Missing {label}"); + } + let queue_position = text.find("8 Queue").unwrap(); + let history_position = text.find("9 History").unwrap(); + assert!(history_position > queue_position); + assert!(!text.contains("Favorites")); + app.key(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Char('8'), + crossterm::event::KeyModifiers::NONE, + )); + let mut terminal = Terminal::new(TestBackend::new(65, 20)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|c| c.symbol()) + .collect::<String>(); + assert!(text.contains("8 Queue")); + } + #[test] + fn cover_caption_shows_playing_artist_independently_of_cursor_and_long_titles() { + let mut app = App::for_tests(); + app.artwork.enabled = true; + app.queue = crate::test_support::songs(); + app.queue[0].artist = "First artist".into(); + app.queue[1].artist = "Next artist".into(); + app.current = Some(0); + app.items = vec![Item::Song(app.queue[1].clone())]; + app.table.select(Some(0)); + app.artwork.title = + "A very long song title that should not push the artist out of view".into(); + for (current, artist) in [(0, "First artist"), (1, "Next artist")] { + app.current = Some(current); + app.paused = true; + let mut terminal = Terminal::new(TestBackend::new(140, 40)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let buffer = terminal.backend().buffer(); + let caption: String = (113..139).map(|x| buffer[(x, 18)].symbol()).collect(); + assert!(caption.contains(artist)); + assert_eq!(buffer[(113, 18)].fg, app.theme.palette().muted); + } + app.current = None; + let mut terminal = Terminal::new(TestBackend::new(140, 40)).unwrap(); + app.view = crate::model::View::Songs { offset: 0 }; + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let caption: String = (113..139) + .map(|x| terminal.backend().buffer()[(x, 18)].symbol()) + .collect(); + assert!(!caption.contains("artist")); + } + + #[test] + fn queue_stays_close_to_cover_as_terminal_height_grows() { + let mut app = App::for_tests(); + app.artwork.enabled = true; + app.artwork.title = "Current cover".into(); + app.queue = crate::test_support::songs(); + app.current = Some(0); + for height in [40, 70] { + let mut terminal = Terminal::new(TestBackend::new(140, height)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let buffer = terminal.backend().buffer(); + let queue_row = (3..height - 7) + .find(|y| { + (112..140) + .map(|x| buffer[(x, *y)].symbol()) + .collect::<String>() + .contains("Queue") + }) + .unwrap(); + // A 26-column square cover uses 13 rows, plus two caption rows and borders. + assert_eq!(queue_row, 20); + assert_eq!(buffer[(112, queue_row - 1)].symbol(), "└"); + assert_eq!(buffer[(139, queue_row - 1)].symbol(), "┘"); + let caption: String = (113..139) + .map(|x| buffer[(x, queue_row - 3)].symbol()) + .collect(); + assert!(caption.contains("Current cover")); + } + } + + #[test] + fn queue_preview_follows_current_track_and_live_edits_without_art() { + let mut app = App::for_tests(); + app.queue = crate::test_support::songs(); + app.current = Some(1); + let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let queue_text = |terminal: &Terminal<TestBackend>| { + let buffer = terminal.backend().buffer(); + (3..23) + .flat_map(|y| (112..140).map(move |x| buffer[(x, y)].symbol())) + .collect::<String>() + }; + let text = queue_text(&terminal); + assert!(text.contains("Queue")); + assert!(text.contains("▶ 2.")); + assert!(text.contains("Track 2")); + assert!(!text.contains("Track 0")); + app.current = Some(2); + app.queue.remove(3); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = queue_text(&terminal); + assert!(text.contains("▶ 3. Track 2")); + assert!(!text.contains("Track 1")); + assert!(!text.contains("Track 3")); + app.artwork.enabled = true; + app.view = crate::model::View::Songs { offset: 0 }; + app.queue.clear(); + app.current = None; + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = queue_text(&terminal); + assert!(text.contains("Cover")); + assert!(text.contains("Queue is empty")); + for (w, h) in [(100, 20), (80, 24)] { + let mut t = Terminal::new(TestBackend::new(w, h)).unwrap(); + t.draw(|f| draw(f, &mut app)).unwrap(); + } + } + #[test] + fn queue_title_and_help_keys_have_visible_theme_accents() { + let mut app = App::for_tests(); + app.queue = crate::test_support::songs(); + let mut terminal = Terminal::new(TestBackend::new(140, 40)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let buffer = terminal.backend().buffer(); + let title = (112..140) + .find_map(|x| (buffer[(x, 3)].symbol() == "Q").then_some(&buffer[(x, 3)])) + .unwrap(); + assert_eq!(title.fg, app.theme.palette().accent); + assert!(title.modifier.contains(Modifier::BOLD)); + app.help = true; + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let key = terminal + .backend() + .buffer() + .content + .windows(21) + .find(|cells| { + cells[0].symbol() == "H" && cells[2].symbol() == "/" && cells[4].symbol() == "L" + }) + .unwrap(); + assert_eq!(key[0].fg, app.theme.palette().accent); + assert_eq!(key[20].fg, app.theme.palette().text); + let selection = app.table.selected(); + app.key(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Char('j'), + crossterm::event::KeyModifiers::NONE, + )); + assert_eq!(app.help_scroll, 1); + assert_eq!(app.table.selected(), selection); + let mut terminal = Terminal::new(TestBackend::new(60, 20)).unwrap(); + app.help_scroll = u16::MAX; + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|c| c.symbol()) + .collect::<String>(); + assert!(text.contains("Download external song")); + assert!(text.contains("Close help")); + } + #[test] + fn full_queue_marks_playback_separately_from_cursor_and_updates_when_paused() { + let mut app = App::for_tests(); + app.queue = crate::test_support::songs(); + app.current = Some(2); + app.key(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Char('8'), + crossterm::event::KeyModifiers::NONE, + )); + assert_eq!(app.table.selected(), Some(2)); + app.table.select(Some(0)); + let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let status_text = |t: &Terminal<TestBackend>| { + let buffer = t.backend().buffer(); + (3..23) + .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol())) + .collect::<String>() + }; + let text = status_text(&terminal); + assert!(text.contains("▶ PLAYING")); + assert!(text.contains("▶ Track 2")); + let buffer = terminal.backend().buffer(); + let marker = (3..23) + .find_map(|y| { + (23..112).find_map(|x| (buffer[(x, y)].symbol() == "▶").then_some(&buffer[(x, y)])) + }) + .unwrap(); + assert_eq!(marker.fg, app.theme.palette().text); + assert!(marker.modifier.contains(Modifier::BOLD)); + app.key(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Char('L'), + crossterm::event::KeyModifiers::SHIFT, + )); + assert_eq!(app.table.selected(), Some(0)); + app.paused = true; + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = status_text(&terminal); + assert!(text.contains("Ⅱ PAUSED")); + assert!(!text.contains("▶ PLAYING")); + assert!(!text.contains("▶ Track 2")); + } + #[test] + fn per_song_download_status_is_visible_in_queue_and_narrow_footer() { + let mut app = App::for_tests(); + let song = crate::test_support::songs().remove(4); + let mut download = crate::downloads::Download::requesting(); + download.update(&crate::downloads::Acquisition { + state: "downloading".into(), + progress: Some(0.42), + source: Some("Soulseek".into()), + ..Default::default() + }); + app.downloads.insert(song.id.clone(), download); + app.queue = vec![song]; + app.key(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Char('8'), + crossterm::event::KeyModifiers::NONE, + )); + for width in [65, 140] { + let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|c| c.symbol()) + .collect::<String>(); + assert!(text.contains("↓ 42%")); + assert!(text.contains("Download: ↓ 42% · Soulseek")); + } + } + #[test] + fn playing_status_survives_download_completion_and_track_changes() { + use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + let mut app = App::for_tests(); + app.queue = crate::test_support::songs() + .into_iter() + .skip(4) + .take(2) + .collect(); + for (i, state) in ["downloading", "done"].into_iter().enumerate() { + let mut download = crate::downloads::Download::requesting(); + download.update(&crate::downloads::Acquisition { + state: state.into(), + progress: Some(0.42), + ..Default::default() + }); + app.downloads.insert(app.queue[i].id.clone(), download); + } + let key = |app: &mut App, c| app.key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)); + key(&mut app, '8'); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap(); + let main_text = |terminal: &Terminal<TestBackend>| { + let buffer = terminal.backend().buffer(); + (3..23) + .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol())) + .collect::<String>() + }; + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = main_text(&terminal); + assert_eq!(text.matches("▶ PLAYING").count(), 1); + assert!(text.contains("[↓ 42%] Track 4")); + key(&mut app, 'L'); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = main_text(&terminal); + assert_eq!(text.matches("▶ PLAYING").count(), 1); + assert!(text.contains("▶ [✓ ADDED] Track 5")); + key(&mut app, ' '); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = main_text(&terminal); + assert!(text.contains("Ⅱ PAUSED")); + assert!(!text.contains("▶ PLAYING")); + assert!(text.contains("[✓ ADDED] Track 5")); + key(&mut app, 'H'); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = main_text(&terminal); + assert!(text.contains("▶ PLAYING")); + assert!(text.contains("▶ [↓ 42%] Track 4")); + } + #[test] + fn playlist_modal_renders_choices_and_name_field_on_small_terminals() { + let mut app = App::for_tests(); + let mut dialog = + crate::playlists::PlaylistDialog::new(1, crate::test_support::songs().remove(0)); + dialog.loading = false; + dialog.choices = vec![crate::playlists::PlaylistChoice { + name: "Evening playlist".into(), + ..Default::default() + }]; + dialog.choices.push(crate::playlists::PlaylistChoice { + id: "station".into(), + name: "Station".into(), + readonly: true, + ..Default::default() + }); + app.playlist_dialog = Some(dialog); + for width in [45, 120] { + let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|c| c.symbol()) + .collect::<String>(); + assert!(text.contains("Add song to playlist")); + assert!(text.contains("Create new playlist")); + assert!(text.contains("Evening playlist")); + assert!(text.contains("Station [read-only]")); + } + app.playlist_dialog.as_mut().unwrap().new_name = Some("Café".into()); + let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|c| c.symbol()) + .collect::<String>(); + assert!(text.contains("Café")); + } + #[test] + fn playlists_show_empty_state_or_actual_load_error() { + let mut app = App::for_tests(); + app.view = crate::model::View::Playlists; + app.items.clear(); + app.loading = false; + let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text: String = terminal + .backend() + .buffer() + .content + .iter() + .map(|c| c.symbol()) + .collect(); + assert!(text.contains("No playlists returned for this account")); + assert!(!text.contains("Octo-only")); + app.load_error = Some("getPlaylists: HTTP 403 Forbidden".into()); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text: String = terminal + .backend() + .buffer() + .content + .iter() + .map(|c| c.symbol()) + .collect(); + assert!(text.contains("HTTP 403 Forbidden")); + assert!(!text.contains("No playlists returned")); + } + + #[test] + fn song_panels_show_years_and_unknown_dates_in_the_year_column() { + use crate::model::{Song, View}; + let songs: Vec<_> = [("Dated", Some(2024)), ("Missing", None), ("Zero", Some(0))] + .into_iter() + .map(|(title, year)| Song { + id: title.into(), + title: title.into(), + year, + ..Default::default() + }) + .collect(); + for view in [ + View::Search("test".into()), + View::Songs { offset: 0 }, + View::Album("album".into()), + View::Artist("artist".into()), + View::ArtistByName("artist".into()), + View::Playlist("list".into()), + View::Queue, + View::History, + View::Discover, + View::Station("station".into()), + View::Radio("song".into()), + View::Genre("Rock".into()), + ] { + let mut app = App::for_tests(); + app.view = view; + app.queue = songs.clone(); + app.items = songs.iter().cloned().map(Item::Song).collect(); + for width in [120, 180] { + let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let buffer = terminal.backend().buffer(); + let year_column = (0..20) + .find_map(|y| { + (23..width - 3).find(|x| { + (*x..*x + 4) + .map(|x| buffer[(x, y)].symbol()) + .collect::<String>() + == "YEAR" + }) + }) + .expect("Year header missing"); + for (title, expected) in [("Dated", "2024"), ("Missing", "—"), ("Zero", "—")] { + let row = (0..20) + .find(|y| { + (23..width - 28) + .map(|x| buffer[(x, *y)].symbol()) + .collect::<String>() + .contains(title) + }) + .unwrap(); + let value: String = (year_column..year_column + 4) + .map(|x| buffer[(x, row)].symbol()) + .collect(); + assert_eq!(value.trim(), expected); + } + } + } + } + + #[test] + fn library_mode_is_visible_and_explains_empty_filtered_views() { + let mut app = App::for_tests(); + app.library_only = true; + app.view = crate::model::View::Radio("song".into()); + app.items.clear(); + app.loading = false; + let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text: String = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect(); + assert!(text.contains("LIBRARY ONLY")); + assert!(text.contains("No library songs in this view")); + assert!(text.contains("m includes online songs")); + app.help = true; + let mut terminal = Terminal::new(TestBackend::new(120, 65)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text: String = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect(); + assert!(text.contains("Toggle library-only mode")); + } + + #[test] + fn artist_tracks_show_album_column_on_medium_and_wide_terminals() { + for view in [ + crate::model::View::Artist("id".into()), + crate::model::View::ArtistByName("Artist".into()), + ] { + let mut app = App::for_tests(); + app.view = view; + app.items = vec![Item::Song(crate::model::Song { + id: "song".into(), + title: "Example song".into(), + artist: "Example artist".into(), + album: "Example album".into(), + ..Default::default() + })]; + for width in [100, 160] { + let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let buffer = terminal.backend().buffer(); + let text: String = (0..20) + .flat_map(|y| (0..width).map(move |x| buffer[(x, y)].symbol())) + .collect(); + assert!(text.contains("ALBUM")); + assert!(text.contains("Example album")); + assert!(text.contains("Example song")); + assert!(!text.contains("ARTIST / ALBUM")); + } + } + } + + #[test] + fn history_shows_clear_empty_state_and_needs_no_server_request() { + let mut app = App::for_tests(); + app.key(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Char('9'), + crossterm::event::KeyModifiers::NONE, + )); + let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = terminal + .backend() + .buffer() + .content + .iter() + .map(|c| c.symbol()) + .collect::<String>(); + assert!(text.contains("No listening history yet")); + assert!(!app.loading); + } + #[test] + fn every_song_panel_marks_current_song_by_id_and_updates_on_track_changes() { + use crate::model::View; + let mut app = App::for_tests(); + let songs = crate::test_support::songs(); + app.queue = songs.clone(); + app.current = Some(1); + // Reverse rows to prove that the marker follows IDs rather than browsing position. + app.items = vec![ + Item::Song(songs[2].clone()), + Item::Song(songs[1].clone()), + Item::Song(songs[0].clone()), + ]; + let main_text = |terminal: &Terminal<TestBackend>| { + let buffer = terminal.backend().buffer(); + (3..23) + .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol())) + .collect::<String>() + }; + for view in [ + View::Search("test".into()), + View::Album("album".into()), + View::Playlist("list".into()), + View::Discover, + View::Station("station".into()), + View::Radio("seed".into()), + View::History, + View::Songs { offset: 0 }, + View::Genre("Rock".into()), + ] { + app.view = view; + app.current = Some(1); + app.paused = false; + let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = main_text(&terminal); + assert_eq!(text.matches("▶ PLAYING").count(), 1); + assert!(text.contains("▶ Track 1")); + app.current = Some(2); + app.paused = true; + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = main_text(&terminal); + assert_eq!(text.matches("Ⅱ PAUSED").count(), 1); + assert!(text.contains("Ⅱ Track 2")); + assert!(!text.contains("▶ Track 1")); + app.current = None; + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let text = main_text(&terminal); + assert!(!text.contains("▶ PLAYING")); + assert!(!text.contains("Ⅱ PAUSED")); + } + } + #[test] + fn queue_duplicate_ids_mark_only_the_active_entry() { + let mut app = App::for_tests(); + let song = crate::test_support::songs().remove(0); + app.queue = vec![song.clone(), song.clone()]; + app.items = vec![Item::Song(song.clone()), Item::Song(song)]; + app.view = crate::model::View::Queue; + app.current = Some(1); + let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + let buffer = terminal.backend().buffer(); + let text = (3..23) + .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol())) + .collect::<String>(); + assert_eq!(text.matches("▶ PLAYING").count(), 1); + } + #[test] + fn renders_small_and_large_terminals() { + let mut app = App::for_tests(); + for (width, height) in [(20, 8), (45, 14), (100, 30), (160, 45)] { + app.theme = app.theme.next(); + let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); + terminal.draw(|f| draw(f, &mut app)).unwrap(); + app.help = true; + terminal.draw(|f| draw(f, &mut app)).unwrap(); + app.help = false; + } + } +}
A
tests/fixtures/acquisitions.json
@@ -0,0 +1,1 @@
+{"subsonic-response":{"status":"ok","version":"1.16.1","type":"octo","acquisitions":{"acquisition":[{"id":"dz-3135556","artist":"Daft Punk","title":"Harder, Better, Faster, Stronger","album":"Discovery","state":"downloading","progress":0.42,"bytesDone":12345,"bytesTotal":29000000,"source":"Soulseek","startedAt":"2026-09-26T18:00:00Z","updatedAt":"2026-09-26T18:00:30Z","error":null,"libraryId":null}]}}}
A
tests/fixtures/search3.json
@@ -0,0 +1,1 @@
+{"subsonic-response":{"status":"ok","version":"1.16.1","type":"navidrome","serverVersion":"0.63.2 (be10f89c)","openSubsonic":true,"searchResult3":{"song":[{"id":"XEjJFBng9tY4swUvEp7Wj7","parent":"7wsVynyqPtHmsFWz6wUDCj","isDir":false,"title":"Nightcall","album":"Nightcall","artist":"Kavinsky","track":1,"year":2024,"genre":"Electro","coverArt":"mf-XEjJFBng9tY4swUvEp7Wj7_6aafffab","size":24740366,"contentType":"audio/flac","suffix":"flac","starred":"2026-09-23T08:00:00Z","duration":179,"bitRate":1032,"path":"Kavinsky/Nightcall/01-01 - Nightcall.flac","playCount":4,"discNumber":1,"created":"2026-09-20T15:51:15.236955739Z","albumId":"7wsVynyqPtHmsFWz6wUDCj","artistId":"1mNJ8hAlbt4jJc2dFaf38y","type":"music","played":"2026-09-22T13:36:41.43536229Z","sortName":"nightcall","mediaType":"song","genres":[{"name":"Electro"}],"replayGain":{},"channelCount":2,"samplingRate":44100,"bitDepth":16,"artists":[{"id":"1mNJ8hAlbt4jJc2dFaf38y","name":"Kavinsky"}],"displayArtist":"Kavinsky","albumArtists":[{"id":"1mNJ8hAlbt4jJc2dFaf38y","name":"Kavinsky"}],"displayAlbumArtist":"Kavinsky • Kavinsky feat. Angèle & Phoenix"},{"id":"4kTq8wQv1YbV1n2m3p4r5s","isDir":false,"title":"The Matrimony (feat. Usher)","album":"The Matrimony (feat. Usher)","artist":"Wale","coverArt":"al-27olR01OlsFec4YYFzCF6M_6ab000f2","size":9480000,"contentType":"audio/mpeg","suffix":"mp3","duration":395,"bitRate":192,"albumId":"27olR01OlsFec4YYFzCF6M","artistId":"0g6CXAjyaR8S9ijOE5tHNn","type":"music"}]}}}