add http-json, rss, and media data source adapters

http-json: generic HTTP+JSON polling adapter, converts serde_json to domain Value. 4 tests.
rss: XML RSS feed parser, extracts items into Value array. 1 test.
media: Navidrome/Subsonic getNowPlaying adapter. 2 tests with fake server.
This commit is contained in:
2026-06-18 22:52:28 +02:00
parent e398c240a0
commit 366d98a1ae
9 changed files with 1076 additions and 2 deletions

View File

@@ -0,0 +1,13 @@
[package]
name = "media-adapter"
version = "0.1.0"
edition = "2024"
[dependencies]
domain.workspace = true
reqwest.workspace = true
serde_json.workspace = true
[dev-dependencies]
tokio.workspace = true
axum.workspace = true

View File

@@ -0,0 +1,158 @@
use std::collections::BTreeMap;
use domain::{DataSource, DataSourcePort, Value};
pub struct MediaAdapter {
client: reqwest::Client,
}
#[derive(Debug)]
pub enum MediaError {
Request(reqwest::Error),
NoUrl,
Parse(String),
}
impl std::fmt::Display for MediaError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MediaError::Request(e) => write!(f, "request: {e}"),
MediaError::NoUrl => write!(f, "no url configured"),
MediaError::Parse(e) => write!(f, "parse: {e}"),
}
}
}
impl MediaAdapter {
pub fn new() -> Self {
Self {
client: reqwest::Client::new(),
}
}
}
impl DataSourcePort for MediaAdapter {
type Error = MediaError;
async fn poll(&self, source: &DataSource) -> Result<Value, Self::Error> {
let base_url = source.config.url.as_ref().ok_or(MediaError::NoUrl)?;
let api_key = source.config.api_key.as_deref().unwrap_or("");
let url = format!(
"{base_url}/rest/getNowPlaying.view?u=kframe&t={api_key}&s=salt&v=1.16.1&c=kframe&f=json"
);
let resp = self.client.get(&url).send().await.map_err(MediaError::Request)?;
let json: serde_json::Value = resp.json().await.map_err(MediaError::Request)?;
let entries = json["subsonic-response"]["nowPlaying"]["entry"]
.as_array()
.cloned()
.unwrap_or_default();
if entries.is_empty() {
let mut result = BTreeMap::new();
result.insert("playing".into(), Value::Bool(false));
return Ok(Value::Object(result));
}
let entry = &entries[0];
let mut result = BTreeMap::new();
result.insert("playing".into(), Value::Bool(true));
result.insert("title".into(), Value::String(
entry["title"].as_str().unwrap_or("Unknown").into()
));
result.insert("artist".into(), Value::String(
entry["artist"].as_str().unwrap_or("Unknown").into()
));
result.insert("album".into(), Value::String(
entry["album"].as_str().unwrap_or("Unknown").into()
));
if let Some(duration) = entry["duration"].as_u64() {
result.insert("duration".into(), Value::Number(duration as f64));
}
Ok(Value::Object(result))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
use domain::{DataSourceConfig, DataSourceType};
fn subsonic_response(playing: bool) -> serde_json::Value {
if playing {
serde_json::json!({
"subsonic-response": {
"status": "ok",
"nowPlaying": {
"entry": [{
"title": "Believer",
"artist": "Imagine Dragons",
"album": "Evolve",
"duration": 204
}]
}
}
})
} else {
serde_json::json!({
"subsonic-response": {
"status": "ok",
"nowPlaying": {}
}
})
}
}
async fn start_fake_subsonic(playing: bool) -> String {
let app = axum::Router::new()
.route("/rest/getNowPlaying.view", axum::routing::get(move || async move {
axum::response::Json(subsonic_response(playing))
}));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
fn make_source(url: String) -> DataSource {
DataSource {
id: 1,
name: "navidrome".into(),
source_type: DataSourceType::Media,
poll_interval: Duration::from_secs(5),
config: DataSourceConfig {
url: Some(url),
headers: vec![],
api_key: Some("testtoken".into()),
},
}
}
#[tokio::test]
async fn returns_now_playing_info() {
let base = start_fake_subsonic(true).await;
let adapter = MediaAdapter::new();
let source = make_source(base);
let result = adapter.poll(&source).await.unwrap();
assert_eq!(result.get_path("$.playing"), Some(&Value::Bool(true)));
assert_eq!(result.get_path("$.title"), Some(&Value::String("Believer".into())));
assert_eq!(result.get_path("$.artist"), Some(&Value::String("Imagine Dragons".into())));
}
#[tokio::test]
async fn returns_not_playing_when_empty() {
let base = start_fake_subsonic(false).await;
let adapter = MediaAdapter::new();
let source = make_source(base);
let result = adapter.poll(&source).await.unwrap();
assert_eq!(result.get_path("$.playing"), Some(&Value::Bool(false)));
}
}