//! The daemon: MPRIS events and a periodic tick go into the [`Engine`];
//! now-playing goes straight to every backend (best effort: a missed one
//! costs nothing), scrobbles go into the [`Queue`], which a drain task sends
//! in batches and retries.
use anyhow::{Context, Result};
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::sync::{Notify, mpsc};
use tracing::{debug, info, warn};
use crate::backend::{HttpBackend, Play, SendError};
use crate::config::Config;
use crate::engine::{Effect, Engine};
use crate::mpris::{self, Event};
use crate::queue::{BATCH, Queue};
/// How often the queue is looked at when nothing new arrives (retries).
const DRAIN_EVERY: Duration = Duration::from_secs(60);
pub fn epoch_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
pub async fn run(config: Config, queue_path: &Path) -> Result<()> {
let backends: Vec<Arc<HttpBackend>> = config
.backends
.iter()
.map(|b| Ok(Arc::new(HttpBackend::new(&b.name, &b.url, &b.token()?))))
.collect::<Result<_>>()?;
if backends.is_empty() {
warn!("no backends configured: plays are only logged");
}
let queue = Arc::new(Mutex::new(
Queue::open(queue_path).with_context(|| format!("opening {}", queue_path.display()))?,
));
let wake = Arc::new(Notify::new());
tokio::spawn(drain(backends.clone(), queue.clone(), wake.clone()));
let conn = zbus::Connection::session()
.await
.context("connecting to the session bus")?;
let (tx, mut rx) = mpsc::channel(256);
tokio::spawn(async move {
if let Err(e) = mpris::watch(conn, tx).await {
warn!(error = %e, "MPRIS watcher stopped");
}
});
let started = Instant::now();
let mono = || started.elapsed().as_millis() as u64;
let mut engine = Engine::new(config.filter());
let mut ticker = tokio::time::interval(Duration::from_secs(config.tick_seconds));
let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
info!(backends = backends.len(), "listening for MPRIS players");
loop {
let effects = tokio::select! {
Some(event) = rx.recv() => match event {
Event::Track { bus_name, track } => {
debug!(player = %bus_name, artist = %track.artist, title = %track.title, "track");
engine.update_metadata(&bus_name, track, mono(), epoch_now())
}
Event::State { bus_name, player, playing } => {
debug!(player = %bus_name, playing, "state");
engine.update_state(&bus_name, &player, playing, mono(), epoch_now())
}
Event::Gone { bus_name } => {
engine.remove(&bus_name);
vec![]
}
},
_ = ticker.tick() => engine.tick(mono()),
_ = tokio::signal::ctrl_c() => break,
_ = sigterm.recv() => break,
};
for effect in effects {
match effect {
Effect::NowPlaying(track) => {
info!(artist = %track.artist, title = %track.title, "now playing");
let play = Play::from_track(&track, None);
for b in &backends {
let (b, play) = (b.clone(), play.clone());
tokio::spawn(async move {
if let Err(e) = b.now_playing(&play).await {
debug!(backend = %b.name, error = %e, "now-playing not sent");
}
});
}
}
Effect::Scrobble(track, started_at) => {
info!(artist = %track.artist, title = %track.title, "scrobble");
let play = Play::from_track(&track, Some(started_at));
let q = queue.lock().expect("queue lock");
for b in &backends {
if let Err(e) = q.push(&b.name, &play) {
warn!(backend = %b.name, error = %e, "couldn't queue a scrobble");
}
}
drop(q);
wake.notify_one();
}
}
}
}
info!("stopping; queued scrobbles are sent next time");
Ok(())
}
/// Send what's due, per backend, whenever woken or every [`DRAIN_EVERY`].
async fn drain(backends: Vec<Arc<HttpBackend>>, queue: Arc<Mutex<Queue>>, wake: Arc<Notify>) {
loop {
for b in &backends {
loop {
let due = match queue.lock().expect("queue lock").due(&b.name, epoch_now()) {
Ok(due) => due,
Err(e) => {
warn!(backend = %b.name, error = %e, "couldn't read the queue");
break;
}
};
if due.is_empty() {
break;
}
let plays: Vec<Play> = due.iter().map(|p| p.play.clone()).collect();
let ids: Vec<i64> = due.iter().map(|p| p.id).collect();
let result = b.scrobble(&plays).await;
let q = queue.lock().expect("queue lock");
let done = match result {
Ok(()) => {
info!(backend = %b.name, count = plays.len(), "scrobbled");
q.remove(&ids)
}
Err(SendError::Rejected(m)) => {
warn!(backend = %b.name, count = plays.len(), reason = %m, "rejected; dropping");
q.remove(&ids)
}
Err(SendError::Retry(m)) => {
warn!(backend = %b.name, count = plays.len(), reason = %m, "will retry");
let _ = q.defer(&due, epoch_now());
break;
}
};
if let Err(e) = done {
warn!(backend = %b.name, error = %e, "couldn't update the queue");
break;
}
if due.len() < BATCH {
break;
}
}
}
tokio::select! {
_ = wake.notified() => {}
_ = tokio::time::sleep(DRAIN_EVERY) => {}
}
}
}
neiam
/scropple-linux
public · Issues · Pulls · Labels · Forks · Compare · Actions success · Badges · Packages
⭐
Log in to mark this repository.
6.4 KiB · text
History
6c56e6c