firefly_music 0.15.1

A Terminal Music Player
Documentation
use std::{sync::Arc, time::Duration};

use color_eyre::eyre;
use mpris_server::{
    LoopStatus, Metadata, PlaybackRate, PlaybackStatus, PlayerInterface, Playlist, PlaylistId,
    PlaylistOrdering, PlaylistsInterface, RootInterface, Time, TrackId, TrackListInterface, Uri,
    Volume,
    zbus::{Result, fdo},
};
use tokio::sync::{RwLock, mpsc::UnboundedSender};
use zbus::{Connection, fdo::DBusProxy, names::BusName};

use crate::{
    global::message::Message, player::message::PlayerMessage, queue::message::QueueMessage,
};

const BUS_NAME_BASE: &str = "Firefly";

/// Store states that MPRIS can retrieve on demand.
pub struct MprisPlayerState {
    pub position: Time,
    pub playback_status: PlaybackStatus,
    pub metadata: Metadata,
    pub volume: Volume,
    pub loop_status: LoopStatus,
}

impl Default for MprisPlayerState {
    fn default() -> Self {
        Self {
            position: Time::ZERO,
            playback_status: PlaybackStatus::Stopped,
            metadata: Metadata::new(),
            volume: 1.0,
            loop_status: LoopStatus::None,
        }
    }
}

pub struct MprisPlayer {
    pub tx: UnboundedSender<Message>,
    pub state: Arc<RwLock<MprisPlayerState>>,
}

impl RootInterface for MprisPlayer {
    async fn raise(&self) -> fdo::Result<()> {
        Ok(())
    }

    async fn quit(&self) -> fdo::Result<()> {
        if let Err(e) = self.tx.send(Message::Quit) {
            log::error!("Error sending Message through async channel: {e}");
        }
        Ok(())
    }

    async fn can_quit(&self) -> fdo::Result<bool> {
        Ok(true)
    }

    async fn fullscreen(&self) -> fdo::Result<bool> {
        Ok(false)
    }

    async fn set_fullscreen(&self, _fullscreen: bool) -> Result<()> {
        Ok(())
    }

    async fn can_set_fullscreen(&self) -> fdo::Result<bool> {
        Ok(false)
    }

    async fn can_raise(&self) -> fdo::Result<bool> {
        Ok(false)
    }

    async fn has_track_list(&self) -> fdo::Result<bool> {
        Ok(false)
    }

    async fn identity(&self) -> fdo::Result<String> {
        Ok("Firefly".to_string())
    }

    async fn desktop_entry(&self) -> fdo::Result<String> {
        Ok("Firefly".to_string())
    }

    async fn supported_uri_schemes(&self) -> fdo::Result<Vec<String>> {
        Ok(vec![])
    }

    async fn supported_mime_types(&self) -> fdo::Result<Vec<String>> {
        Ok(vec![])
    }
}

impl PlayerInterface for MprisPlayer {
    async fn next(&self) -> fdo::Result<()> {
        log::info!("Mpris called next().");
        if let Err(e) = self.tx.send(Message::Player(PlayerMessage::Next)) {
            log::error!("Error sending Message through async channel: {e}");
        }

        Ok(())
    }

    async fn previous(&self) -> fdo::Result<()> {
        log::info!("Mpris called previous().");
        if let Err(e) = self.tx.send(Message::Player(PlayerMessage::PreviousTrack)) {
            log::error!("Error sending Message through async channel: {e}");
        }
        Ok(())
    }

    async fn pause(&self) -> fdo::Result<()> {
        log::info!("Mpris called pause().");
        if let Err(e) = self.tx.send(Message::Player(PlayerMessage::Pause)) {
            log::error!("Error sending Message through async channel: {e}");
        }
        Ok(())
    }

    async fn play_pause(&self) -> fdo::Result<()> {
        log::info!("Mpris called play_pause().");
        if let Err(e) = self.tx.send(Message::Player(PlayerMessage::TogglePlay)) {
            log::error!("Error sending Message through async channel: {e}");
        }
        Ok(())
    }

    async fn stop(&self) -> fdo::Result<()> {
        log::info!("Mpris called stop().");
        if let Err(e) = self
            .tx
            .send(Message::Player(PlayerMessage::ClearCurrentSession))
        {
            log::error!("Error sending Message through async channel: {e}");
        }
        Ok(())
    }

    async fn play(&self) -> fdo::Result<()> {
        log::info!("Mpris called play().");
        if let Err(e) = self.tx.send(Message::Player(PlayerMessage::Play)) {
            log::error!("Error sending Message through async channel: {e}");
        }
        Ok(())
    }

    async fn seek(&self, offset: Time) -> fdo::Result<()> {
        log::info!("Mpris called seek().");
        log::info!("Seek time: {:?}", offset.as_secs());
        if let Err(e) = self
            .tx
            .send(Message::Player(PlayerMessage::SeekOffset(offset)))
        {
            log::error!("Error sending Message through async channel: {e}");
        }
        Ok(())
    }

    async fn set_position(&self, _track_id: TrackId, position: Time) -> fdo::Result<()> {
        log::info!("Mpris called set_position().");
        if let Err(e) = self.tx.send(Message::Player(PlayerMessage::SetPosition(
            Duration::from_secs(position.as_secs() as u64),
        ))) {
            log::error!("Error sending Message through async channel: {e}");
        }
        log::info!("Mpris set position to {:?}.", position);

        Ok(())
    }
    async fn position(&self) -> fdo::Result<Time> {
        log::info!("Mpris called position().");

        let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();

        if let Err(e) = self
            .tx
            .send(Message::Player(PlayerMessage::SyncMprisPos(done_tx)))
        {
            log::error!("Error sending Message through async channel: {e}");
        }

        let _ = done_rx.await;

        let pos = self.state.read().await.position;

        log::info!("Mpris retrieved position: {}", pos.as_micros());
        Ok(pos)
    }

    async fn open_uri(&self, _uri: String) -> fdo::Result<()> {
        log::info!("Mpris called open_uri().");
        Ok(())
    }

    async fn playback_status(&self) -> fdo::Result<PlaybackStatus> {
        log::info!("Mpris called playback_status().");
        Ok(self.state.read().await.playback_status)
    }

    async fn loop_status(&self) -> fdo::Result<LoopStatus> {
        log::info!("Mpris called loop_status().");
        Ok(self.state.read().await.loop_status)
    }

    async fn set_loop_status(&self, _loop_status: LoopStatus) -> Result<()> {
        if let Err(e) = self.tx.send(Message::Player(PlayerMessage::ToggleLoop)) {
            log::error!("Error sending Message through async channel: {e}");
        }
        Ok(())
    }

    async fn rate(&self) -> fdo::Result<PlaybackRate> {
        log::info!("Mpris called rate().");
        Ok(1.0)
    }

    async fn set_rate(&self, _rate: PlaybackRate) -> Result<()> {
        Ok(())
    }

    async fn shuffle(&self) -> fdo::Result<bool> {
        Ok(false)
    }

    async fn set_shuffle(&self, _shuffle: bool) -> Result<()> {
        if let Err(e) = self.tx.send(Message::Queue(QueueMessage::Shuffle)) {
            log::error!("Error sending Message through async channel: {e}");
        }
        Ok(())
    }

    async fn metadata(&self) -> fdo::Result<Metadata> {
        log::info!("Mpris called metadata().");
        Ok(self.state.read().await.metadata.clone())
    }

    async fn volume(&self) -> fdo::Result<Volume> {
        log::info!("Mpris called volume().");
        let vol = self.state.read().await.volume;

        log::info!("Mpris retrieved volume: {:?}.", vol);

        Ok(vol)
    }

    async fn set_volume(&self, volume: Volume) -> Result<()> {
        if let Err(e) = self.tx.send(Message::Player(PlayerMessage::SetVolume(
            ((volume * 1000.0).round() / 1000.0) as f32,
        ))) {
            log::error!("Error sending Message through async channel: {e}");
        }
        log::info!("Mpris set volume to {:?}.", volume);

        Ok(())
    }

    async fn minimum_rate(&self) -> fdo::Result<PlaybackRate> {
        Ok(1.0)
    }

    async fn maximum_rate(&self) -> fdo::Result<PlaybackRate> {
        Ok(1.0)
    }

    async fn can_go_next(&self) -> fdo::Result<bool> {
        Ok(true)
    }

    async fn can_go_previous(&self) -> fdo::Result<bool> {
        Ok(true)
    }

    async fn can_play(&self) -> fdo::Result<bool> {
        Ok(true)
    }

    async fn can_pause(&self) -> fdo::Result<bool> {
        Ok(true)
    }

    async fn can_seek(&self) -> fdo::Result<bool> {
        Ok(true)
    }

    async fn can_control(&self) -> fdo::Result<bool> {
        Ok(true)
    }
}

impl TrackListInterface for MprisPlayer {
    async fn get_tracks_metadata(&self, track_ids: Vec<TrackId>) -> fdo::Result<Vec<Metadata>> {
        println!("GetTracksMetadata({track_ids:?})");
        Ok(vec![])
    }

    async fn add_track(
        &self,
        uri: Uri,
        after_track: TrackId,
        set_as_current: bool,
    ) -> fdo::Result<()> {
        println!("AddTrack({uri}, {after_track}, {set_as_current})");
        Ok(())
    }

    async fn remove_track(&self, track_id: TrackId) -> fdo::Result<()> {
        println!("RemoveTrack({track_id})");
        Ok(())
    }

    async fn go_to(&self, track_id: TrackId) -> fdo::Result<()> {
        println!("GoTo({track_id})");
        Ok(())
    }

    async fn tracks(&self) -> fdo::Result<Vec<TrackId>> {
        println!("Tracks");
        Ok(vec![])
    }

    async fn can_edit_tracks(&self) -> fdo::Result<bool> {
        println!("CanEditTracks");
        Ok(false)
    }
}

impl PlaylistsInterface for MprisPlayer {
    async fn activate_playlist(&self, _playlist_id: PlaylistId) -> fdo::Result<()> {
        Ok(())
    }

    async fn get_playlists(
        &self,
        _index: u32,
        _max_count: u32,
        _order: PlaylistOrdering,
        _reverse_order: bool,
    ) -> fdo::Result<Vec<Playlist>> {
        Ok(vec![])
    }

    async fn playlist_count(&self) -> fdo::Result<u32> {
        Ok(0)
    }

    async fn orderings(&self) -> fdo::Result<Vec<PlaylistOrdering>> {
        Ok(vec![])
    }

    async fn active_playlist(&self) -> fdo::Result<Option<Playlist>> {
        Ok(None)
    }
}

pub async fn bus_name_is_used(name: &str) -> eyre::Result<bool> {
    let connection = Connection::session().await?;

    let proxy = DBusProxy::new(&connection).await?;

    let bus_name = format!("org.mpris.MediaPlayer2.{}", name);

    if proxy.name_has_owner(BusName::try_from(bus_name)?).await? {
        Ok(true)
    } else {
        Ok(false)
    }
}

pub async fn get_bus_name() -> String {
    let mut n = 0;
    let bus_name = loop {
        let candidate = if n == 0 {
            BUS_NAME_BASE.to_string()
        } else {
            format!("{BUS_NAME_BASE}{n}")
        };

        if let Ok(bool) = bus_name_is_used(&candidate).await {
            if !bool {
                break candidate;
            }
        } else {
            log::error!("Error checking bus name. Possibly not on Linux.");
            break String::new();
        }

        n += 1;
    };

    bus_name
}