feat: add CLI args, health endpoint, and fix torznab search

- Add clap for CLI argument parsing (-c config, -p port)
- Add health endpoint showing service status at /api/health
- Add IndexerType enum for auto URL construction (jackett/prowlarr/torznab)
- Fix Axum 0.8 route syntax ({param} instead of :param)
- Fix torznab search to use 'q' param instead of artist/album (Jackett only supports q)
This commit is contained in:
Alexander
2026-04-28 19:16:22 +02:00
parent 5afcbd68ad
commit 925c7c3703
11 changed files with 235 additions and 22 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ pub fn routes() -> Router<AppState> {
Router::new()
.route("/", get(list_indexers))
.route("/search", post(search))
.route("/:name/test", get(test_indexer))
.route("/{name}/test", get(test_indexer))
}
async fn list_indexers(State(state): State<AppState>) -> Json<Vec<IndexerInfo>> {
+4 -4
View File
@@ -12,11 +12,11 @@ use crate::AppState;
pub fn routes() -> Router<AppState> {
Router::new()
.route("/artists/search", get(search_artists))
.route("/artists/:id", get(get_artist))
.route("/artists/:id/albums", get(get_artist_albums))
.route("/artists/{id}", get(get_artist))
.route("/artists/{id}/albums", get(get_artist_albums))
.route("/artists/sync", post(sync_artist))
.route("/albums/:id", get(get_album))
.route("/albums/:id/tracks", get(get_album_tracks))
.route("/albums/{id}", get(get_album))
.route("/albums/{id}/tracks", get(get_album_tracks))
.route("/status", get(connection_status))
}
+34 -2
View File
@@ -16,10 +16,11 @@ use crate::AppState;
pub fn routes(state: AppState) -> Router {
Router::new()
.route("/health", get(health))
.route("/tracks", get(list_tracks))
.route("/tracks", post(create_track))
.route("/tracks/:id", get(get_track))
.route("/tracks/:id", delete(delete_track))
.route("/tracks/{id}", get(get_track))
.route("/tracks/{id}", delete(delete_track))
.route("/tracks/search", get(search_tracks))
.route("/stats", get(get_stats))
.nest("/indexers", indexer_controller::routes())
@@ -28,6 +29,37 @@ pub fn routes(state: AppState) -> Router {
.with_state(state)
}
#[derive(serde::Serialize)]
struct Health {
status: &'static str,
services: ServiceStatus,
}
#[derive(serde::Serialize)]
struct ServiceStatus {
torrent: bool,
metadata: bool,
indexers: Vec<String>,
}
async fn health(State(state): State<AppState>) -> Json<Health> {
let state = state.read().await;
let indexers = state
.indexer_service
.list_indexers()
.into_iter()
.map(|i| i.name)
.collect();
Json(Health {
status: "ok",
services: ServiceStatus {
torrent: state.torrent_service.is_connected().await,
metadata: state.metadata_service.is_connected(),
indexers,
},
})
}
async fn list_tracks(State(state): State<AppState>) -> Json<Vec<Track>> {
let state = state.read().await;
Json(state.aggregator.get_all().to_vec())
+4 -4
View File
@@ -12,10 +12,10 @@ use crate::AppState;
pub fn routes() -> Router<AppState> {
Router::new()
.route("/", get(list_torrents))
.route("/:hash", get(get_torrent))
.route("/:hash", delete(remove_torrent))
.route("/:hash/pause", post(pause_torrent))
.route("/:hash/resume", post(resume_torrent))
.route("/{hash}", get(get_torrent))
.route("/{hash}", delete(remove_torrent))
.route("/{hash}/pause", post(pause_torrent))
.route("/{hash}/resume", post(resume_torrent))
.route("/add/url", post(add_torrent_url))
.route("/add/file", post(add_torrent_file))
.route("/status", get(connection_status))
+31
View File
@@ -14,12 +14,32 @@ pub enum ConfigError {
#[derive(Debug, Clone, Deserialize)]
pub struct Config {
#[serde(default)]
pub app: AppConfig,
pub database: DatabaseConfig,
pub metadata: MetadataConfig,
pub indexers: Vec<IndexerConfig>,
pub torrent: TorrentConfig,
}
#[derive(Debug, Clone, Deserialize)]
pub struct AppConfig {
#[serde(default = "default_port")]
pub port: u16,
}
impl Default for AppConfig {
fn default() -> Self {
Self {
port: default_port(),
}
}
}
fn default_port() -> u16 {
3000
}
#[derive(Debug, Clone, Deserialize)]
pub struct MetadataConfig {
pub endpoint: String,
@@ -30,9 +50,20 @@ pub struct DatabaseConfig {
pub url: String,
}
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum IndexerType {
#[default]
Jackett,
Prowlarr,
Torznab,
}
#[derive(Debug, Clone, Deserialize)]
pub struct IndexerConfig {
pub name: String,
#[serde(default)]
pub indexer_type: IndexerType,
pub url: String,
pub api_key: String,
}
+4 -5
View File
@@ -53,15 +53,14 @@ impl TorznabIndexer {
.join(",");
query.append_pair("cat", &cats);
query.append_pair("artist", &criteria.clean_artist());
let mut q_parts = vec![criteria.clean_artist()];
if let Some(album) = criteria.clean_album() {
query.append_pair("album", &album);
q_parts.push(album);
}
if let Some(year) = criteria.year {
query.append_pair("year", &year.to_string());
q_parts.push(year.to_string());
}
query.append_pair("q", &q_parts.join(" "));
query.append_pair("limit", &criteria.limit.to_string());
query.append_pair("offset", &criteria.offset.to_string());
+19 -4
View File
@@ -2,6 +2,7 @@ use std::sync::Arc;
use tokio::sync::RwLock;
use axum::Router;
use clap::Parser;
use music_agregator::{
api, config,
services::{IndexerService, MetadataService, TorrentService},
@@ -11,6 +12,17 @@ use tower_http::cors::{Any, CorsLayer};
use tower_http::trace::TraceLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[derive(Parser)]
#[command(name = "music-agregator")]
#[command(about = "Music aggregation service with torrent and metadata integration")]
struct Args {
#[arg(short, long, default_value = "config.yaml")]
config: String,
#[arg(short, long)]
port: Option<u16>,
}
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
@@ -18,10 +30,11 @@ async fn main() {
.with(tracing_subscriber::EnvFilter::from_default_env())
.init();
let config_path = std::env::var("CONFIG_PATH").unwrap_or_else(|_| "config.yaml".to_string());
let config = match config::Config::load(&config_path) {
let args = Args::parse();
let config = match config::Config::load(&args.config) {
Ok(cfg) => {
tracing::info!("loaded config from {}", config_path);
tracing::info!("loaded config from {}", args.config);
cfg
}
Err(e) => {
@@ -92,7 +105,9 @@ async fn main() {
.layer(cors)
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
let port = args.port.unwrap_or(config.app.port);
let addr = format!("0.0.0.0:{}", port);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
tracing::info!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
}
+12 -2
View File
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use std::sync::Arc;
use crate::config::IndexerConfig;
use crate::config::{IndexerConfig, IndexerType};
use crate::indexer::{Indexer, IndexerError, MusicSearchCriteria, SearchResult, TorznabIndexer};
pub struct IndexerService {
@@ -19,13 +19,23 @@ impl IndexerService {
let mut service = Self::new();
for config in configs {
let indexer = TorznabIndexer::new(&config.name, &config.url, &config.api_key)?;
let torznab_url = Self::build_torznab_url(&config.url, config.indexer_type);
let indexer = TorznabIndexer::new(&config.name, &torznab_url, &config.api_key)?;
service.add_indexer(Arc::new(indexer));
}
Ok(service)
}
fn build_torznab_url(base_url: &str, indexer_type: IndexerType) -> String {
let base = base_url.trim_end_matches('/');
match indexer_type {
IndexerType::Jackett => format!("{}/api/v2.0/indexers/all/results/torznab/", base),
IndexerType::Prowlarr => format!("{}/api/v1/indexer/all/torznab", base),
IndexerType::Torznab => base_url.to_string(),
}
}
pub fn add_indexer(&mut self, indexer: Arc<dyn Indexer>) {
self.indexers.insert(indexer.name().to_string(), indexer);
}