summaryrefslogtreecommitdiffstats
path: root/src/dbus/player.rs
blob: a78d7ed644e70476db9f6eb5c5cdf6e5b0168bbc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//! # D-Bus interface proxy for: `org.mpris.MediaPlayer2.Player`
//!
//! This code was generated by `zbus-xmlgen` `4.1.0` from D-Bus introspection data.
//! Source: `Interface '/org/mpris/MediaPlayer2' from service 'org.mpris.MediaPlayer2.playerctld' on system bus`.
//!
//! You may prefer to adapt it, instead of using it verbatim.
//!
//! More information can be found in the [Writing a client proxy] section of the zbus
//! documentation.
//!
//! This type implements the [D-Bus standard interfaces], (`org.freedesktop.DBus.*`) for which the
//! following zbus API can be used:
//!
//! * [`zbus::fdo::PropertiesProxy`]
//! * [`zbus::fdo::IntrospectableProxy`]
//! * [`zbus::fdo::PeerProxy`]
//!
//! Consequently `zbus-xmlgen` did not generate code for the above interfaces.
//!
//! [Writing a client proxy]: https://dbus2.github.io/zbus/client.html
//! [D-Bus standard interfaces]: https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces,

use std::collections::HashMap;

use serde::{ser::Error, Deserialize, Serialize};
use time::{format_description::well_known::Iso8601, PrimitiveDateTime};
use url::Url;
use zbus::{
    proxy,
    zvariant::{OwnedValue, Type},
};

#[proxy(
    interface = "org.mpris.MediaPlayer2.Player",
    default_service = "org.mpris.MediaPlayer2.playerctld",
    default_path = "/org/mpris/MediaPlayer2"
)]
trait Player {
    /// Next method
    fn next(&self) -> zbus::Result<()>;

    /// OpenUri method
    fn open_uri(&self, uri: &str) -> zbus::Result<()>;

    /// Pause method
    fn pause(&self) -> zbus::Result<()>;

    /// Play method
    fn play(&self) -> zbus::Result<()>;

    /// PlayPause method
    fn play_pause(&self) -> zbus::Result<()>;

    /// Previous method
    fn previous(&self) -> zbus::Result<()>;

    /// Seek method
    fn seek(&self, offset: i64) -> zbus::Result<()>;

    /// SetPosition method
    fn set_position(
        &self,
        track_id: &zbus::zvariant::ObjectPath<'_>,
        offset: i64,
    ) -> zbus::Result<()>;

    /// Stop method
    fn stop(&self) -> zbus::Result<()>;

    /// Seeked signal
    #[zbus(signal)]
    fn seeked(&self, position: i64) -> zbus::Result<()>;

    /// CanControl property
    #[zbus(property)]
    fn can_control(&self) -> zbus::Result<bool>;

    /// CanGoNext property
    #[zbus(property)]
    fn can_go_next(&self) -> zbus::Result<bool>;

    /// CanGoPrevious property
    #[zbus(property)]
    fn can_go_previous(&self) -> zbus::Result<bool>;

    /// CanPause property
    #[zbus(property)]
    fn can_pause(&self) -> zbus::Result<bool>;

    /// CanPlay property
    #[zbus(property)]
    fn can_play(&self) -> zbus::Result<bool>;

    /// CanSeek property
    #[zbus(property)]
    fn can_seek(&self) -> zbus::Result<bool>;

    /// LoopStatus property
    #[zbus(property)]
    fn loop_status(&self) -> zbus::Result<String>;
    #[zbus(property)]
    fn set_loop_status(&self, value: &str) -> zbus::Result<()>;

    /// MaximumRate property
    #[zbus(property)]
    fn maximum_rate(&self) -> zbus::Result<f64>;

    /// Metadata property
    #[zbus(property)]
    fn metadata(&self) -> zbus::Result<Metadata>;

    /// MinimumRate property
    #[zbus(property)]
    fn minimum_rate(&self) -> zbus::Result<f64>;

    /// PlaybackStatus property
    #[zbus(property)]
    fn playback_status(&self) -> zbus::Result<PlaybackStatus>;

    /// Position property
    #[zbus(property)]
    fn position(&self) -> zbus::Result<i64>;

    /// Rate property
    #[zbus(property)]
    fn rate(&self) -> zbus::Result<f64>;
    #[zbus(property)]
    fn set_rate(&self, value: f64) -> zbus::Result<()>;

    /// Shuffle property
    #[zbus(property)]
    fn shuffle(&self) -> zbus::Result<bool>;
    #[zbus(property)]
    fn set_shuffle(&self, value: bool) -> zbus::Result<()>;

    /// Volume property
    #[zbus(property)]
    fn volume(&self) -> zbus::Result<f64>;
    #[zbus(property)]
    fn set_volume(&self, value: f64) -> zbus::Result<()>;
}

/// MPRIS metadata recomended fields
///
/// Found here: [https://www.freedesktop.org/wiki/Specifications/mpris-spec/metadata]
#[derive(Debug, Default, PartialEq, Type, Serialize, Deserialize)]
#[zvariant(signature = "dict")]
pub struct Metadata {
    /// D-Bus path: A unique identity for this track within the context of an MPRIS object (eg: tracklist).
    #[zvariant(rename = "mpris:trackid")]
    pub trackid: Option<String>,

    /// 64-bit integer: The duration of the track in microseconds.
    #[zvariant(rename = "mpris:length")]
    pub length: Option<u64>,

    /// URI: The location of an image representing the track or album. Clients should not assume this will continue to exist when the media player stops giving out the URL.
    #[zvariant(rename = "mpris:artUrl")]
    pub art_url: Option<url::Url>,

    /// String: The album name.
    #[zvariant(rename = "xesam:album")]
    pub album: Option<String>,

    /// List of Strings: The album artist(s).
    #[zvariant(rename = "xesam:albumArtist")]
    pub album_artist: Option<Vec<String>>,

    /// List of Strings: The track artist(s).
    #[zvariant(rename = "xesam:artist")]
    pub artist: Option<Vec<String>>,

    /// String: The track lyrics.
    #[zvariant(rename = "xesam:asText")]
    pub as_text: Option<String>,

    /// Integer: The speed of the music, in beats per minute.
    #[zvariant(rename = "xesam:audioBPM")]
    pub audio_bpm: Option<u64>,

    /// Float: An automatically-generated rating, based on things such as how often it has been played. This should be in the range 0.0 to 1.0.
    #[zvariant(rename = "xesam:autoRating")]
    pub auto_rating: Option<f64>,

    /// List of Strings: A (list of) freeform comment(s).
    #[zvariant(rename = "xesam:comment")]
    pub comment: Option<Vec<String>>,

    /// List of Strings: The composer(s) of the track.
    #[zvariant(rename = "xesam:composer")]
    pub composer: Option<Vec<String>>,

    /// Date/Time: When the track was created. Usually only the year component will be useful.
    #[zvariant(rename = "xesam:contentCreated")]
    pub content_created: Option<PrimitiveDateTime>,

    /// Integer: The disc number on the album that this track is from.
    #[zvariant(rename = "xesam:discNumber")]
    pub disc_number: Option<u64>,

    /// Date/Time: When the track was first played.
    #[zvariant(rename = "xesam:firstUsed")]
    pub first_used: Option<PrimitiveDateTime>,

    /// List of Strings: The genre(s) of the track.
    #[zvariant(rename = "xesam:genre")]
    pub genre: Option<Vec<String>>,

    /// Date/Time: When the track was last played.
    #[zvariant(rename = "xesam:lastUsed")]
    pub last_used: Option<PrimitiveDateTime>,

    /// List of Strings: The lyricist(s) of the track.
    #[zvariant(rename = "xesam:lyricist")]
    pub lyricist: Option<Vec<String>>,

    /// String: The track title.
    #[zvariant(rename = "xesam:title")]
    pub title: Option<String>,

    /// Integer: The track number on the album disc.
    #[zvariant(rename = "xesam:trackNumber")]
    pub track_number: Option<u64>,

    /// URI: The location of the media file.
    #[zvariant(rename = "xesam:url")]
    pub url: Option<url::Url>,

    /// Integer: The number of times the track has been played.
    #[zvariant(rename = "xesam:useCount")]
    pub use_count: Option<u64>,

    /// Float: A user-specified rating. This should be in the range 0.0 to 1.0.
    #[zvariant(rename = "xesam:userRating")]
    pub user_rating: Option<f64>,
}

impl TryFrom<OwnedValue> for Metadata {
    type Error = zbus::zvariant::Error;

    fn try_from(value: OwnedValue) -> Result<Self, Self::Error> {
        let map: HashMap<String, OwnedValue> = value.try_into()?;

        macro_rules! get_field {
            ($n:literal, PrimitiveDateTime) => {
                get_field!($n)
                    .map(|s: String| PrimitiveDateTime::parse(&s, &Iso8601::DEFAULT))
                    .transpose()
                    .map_err(Self::Error::custom)?
            };
            ($n:literal, Url) => {
                get_field!($n)
                    .map(|s: String| Url::parse(&s))
                    .transpose()
                    .map_err(Self::Error::custom)?
            };
            ($n:literal) => {
                map.get($n)
                    .map(|o| o.try_to_owned())
                    .transpose()?
                    .map(|o| o.try_into())
                    .transpose()?
            };
        }

        Ok(Metadata {
            trackid: get_field!("mpris:trackid"),
            length: get_field!("mpris:length"),
            art_url: get_field!("mpris:artUrl", Url),
            album: get_field!("xesam:album"),
            album_artist: get_field!("xesam:albumArtist"),
            artist: get_field!("xesam:artist"),
            as_text: get_field!("xesam:asText"),
            audio_bpm: get_field!("xesam:audioBPM"),
            auto_rating: get_field!("xesam:autoRating"),
            comment: get_field!("xesam:comment"),
            composer: get_field!("xesam:composer"),
            content_created: get_field!("xesam:contentCreated", PrimitiveDateTime),
            disc_number: get_field!("xesam:discNumber"),
            first_used: get_field!("xesam:firstUsed", PrimitiveDateTime),
            genre: get_field!("xesam:genre"),
            last_used: get_field!("xesam:lastUsed", PrimitiveDateTime),
            lyricist: get_field!("xesam:lyricist"),
            title: get_field!("xesam:title"),
            track_number: get_field!("xesam:trackNumber"),
            url: get_field!("xesam:url", Url),
            use_count: get_field!("xesam:useCount"),
            user_rating: get_field!("xesam:userRating"),
        })
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Type)]
pub enum PlaybackStatus {
    Playing,
    Paused,
    #[default]
    Stopped,
}

impl TryFrom<OwnedValue> for PlaybackStatus {
    type Error = zbus::Error;

    fn try_from(value: OwnedValue) -> Result<Self, Self::Error> {
        match value.downcast_ref()? {
            "Playing" => Ok(Self::Playing),
            "Paused" => Ok(Self::Paused),
            "Stopped" => Ok(Self::Stopped),
            _ => Err(zbus::Error::InvalidField),
        }
    }
}