mprisqueeze 0.1.11

A command-line client for controlling squeezelite via MPRIS
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! The functions to talk to the LMS server. LMS accepts and returns JSON data. The requests are
//! created using the functions in the [request] module.
use crate::lms::request::LmsRequest;
use anyhow::bail;
use anyhow::{Ok, Result, anyhow};
use log::debug;
use reqwest::Client;
use serde::Deserialize;
use serde_json::Value;
use thiserror::Error;
use tokio::sync::mpsc;

mod request;

#[derive(Debug, PartialEq, Eq)]
pub enum Mode {
    Stop,
    Play,
    Pause,
}

#[derive(Debug, PartialEq, Eq)]
pub enum Shuffle {
    Off,
    Songs,
    Albums,
}

#[derive(Debug, Clone)]
pub struct LmsClient {
    /// The HTTP client
    client: Client,
    /// The URL to reach the LMS server
    url: String,
    /// The hostname of the LMS server
    hostname: String,
    /// The port of the LMS server
    port: u16,
    /// The channel to report errors
    sender: mpsc::Sender<anyhow::Error>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct Player {
    pub name: String,
    pub playerid: String,
}

impl LmsClient {
    pub fn new(hostname: String, port: u16) -> (Self, mpsc::Receiver<anyhow::Error>) {
        let client = Client::new();
        let url = format!("http://{}:{}/jsonrpc.js", hostname, port);
        let (sender, receiver) = mpsc::channel::<anyhow::Error>(1);

        (
            Self {
                client,
                url,
                hostname,
                port,
                sender,
            },
            receiver,
        )
    }

    pub fn cover_art_url(&self, player_id: &str) -> String {
        format!(
            "http://{}:{}/music/current/cover.jpg?player={}",
            self.hostname, self.port, player_id
        )
    }

    #[allow(dead_code)]
    pub async fn get_version(&self) -> Result<String> {
        self.handle_error(
            (|| async {
                let (request, field) = LmsRequest::version();
                let lms_response = self.post(&request).await?;
                as_string(lms_response, &field)
            })()
            .await,
            anyhow!("Error get_version"),
        )
        .await
    }

    #[allow(dead_code)]
    pub async fn get_connected(&self, name: String) -> Result<bool> {
        self.handle_error(
            (|| async {
                let (request, field) = LmsRequest::connected(name);
                let lms_response = self.post(&request).await?;
                as_bool(lms_response, &field)
            })()
            .await,
            anyhow!("Error get_connected"),
        )
        .await
    }

    pub async fn get_player_count(&self) -> Result<u64> {
        self.handle_error(
            (|| async {
                let (request, field) = LmsRequest::player_count();
                let lms_response = self.post(&request).await?;
                as_u64(lms_response, &field)
            })()
            .await,
            anyhow!("Error player_count"),
        )
        .await
    }

    pub async fn get_players(&self) -> Result<Vec<Player>> {
        self.handle_error(
            (|| async {
                let (request, field) = LmsRequest::players();
                let lms_response = self.post(&request).await?;
                let value = result_field(lms_response, &field)?.clone();
                serde_json::from_value(value.to_owned()).map_err(|e| e.into())
            })()
            .await,
            anyhow!("Error get_players"),
        )
        .await
    }

    pub async fn get_index(&self, name: String) -> Result<u64> {
        self.handle_error(
            (|| async {
                let (request, field) = LmsRequest::index(name);
                let lms_response = self.post(&request).await?;
                as_u64(lms_response, &field)
            })()
            .await,
            anyhow!("Error get_index"),
        )
        .await
    }

    pub async fn get_track_count(&self, name: String) -> Result<u64> {
        self.handle_error(
            (|| async {
                let (request, field) = LmsRequest::track_count(name);
                let lms_response = self.post(&request).await?;
                as_u64(lms_response, &field)
            })()
            .await,
            anyhow!("Error get_track_count"),
        )
        .await
    }

    pub async fn get_shuffle(&self, name: String) -> Result<Shuffle> {
        self.handle_error(
            (|| async {
                let (request, field) = LmsRequest::shuffle(name);
                let lms_response = self.post(&request).await?;
                as_shuffle(lms_response, &field)
            })()
            .await,
            anyhow!("Error get_shuffle"),
        )
        .await
    }

    pub async fn get_mode(&self, name: String) -> Result<Mode> {
        self.handle_error(
            (|| async {
                let (request, field) = LmsRequest::mode(name);
                let lms_response = self.post(&request).await?;
                as_mode(lms_response, &field)
            })()
            .await,
            anyhow!("Error get_mode"),
        )
        .await
    }

    // When the playlist is empty, the `field` is not here. The `result` field contains an empty
    // object.
    pub async fn get_artist(&self, name: String) -> Result<Option<String>> {
        self.handle_error(
            (|| async {
                let (request, field) = LmsRequest::artist(name);
                let lms_response = self.post(&request).await?;
                as_string_or_not_there(lms_response, &field)
            })()
            .await,
            anyhow!("Error get_artist"),
        )
        .await
    }

    // Same remark as [`get_artist`]
    pub async fn get_title(&self, name: String) -> Result<Option<String>> {
        self.handle_error(
            (|| async {
                let (request, field) = LmsRequest::title(name);
                let lms_response = self.post(&request).await?;
                as_string_or_not_there(lms_response, &field)
            })()
            .await,
            anyhow!("Error get_title"),
        )
        .await
    }

    // ditto
    pub async fn get_album(&self, name: String) -> Result<Option<String>> {
        self.handle_error(
            (|| async {
                let (request, field) = LmsRequest::album(name);
                let lms_response = self.post(&request).await?;
                as_string_or_not_there(lms_response, &field)
            })()
            .await,
            anyhow!("Error get_album"),
        )
        .await
    }

    pub async fn play(&self, name: String) -> Result<()> {
        self.handle_error(
            self.post_no_result(&LmsRequest::play(name)).await,
            anyhow!("Error play"),
        )
        .await
    }

    pub async fn stop(&self, name: String) -> Result<()> {
        self.handle_error(
            self.post_no_result(&LmsRequest::stop(name)).await,
            anyhow!("Error stop"),
        )
        .await
    }

    pub async fn pause(&self, name: String) -> Result<()> {
        self.handle_error(
            self.post_no_result(&LmsRequest::pause(name)).await,
            anyhow!("Error pause"),
        )
        .await
    }

    pub async fn play_pause(&self, name: String) -> Result<()> {
        self.handle_error(
            self.post_no_result(&LmsRequest::play_pause(name)).await,
            anyhow!("Error play_pause"),
        )
        .await
    }

    pub async fn previous(&self, name: String) -> Result<()> {
        self.handle_error(
            self.post_no_result(&LmsRequest::previous(name)).await,
            anyhow!("Error previous"),
        )
        .await
    }

    pub async fn next(&self, name: String) -> Result<()> {
        self.handle_error(
            self.post_no_result(&LmsRequest::next(name)).await,
            anyhow!("Error next"),
        )
        .await
    }

    // The error is not passed to the client but sent to the error channel
    async fn handle_error<T: std::fmt::Debug>(
        &self,
        result: Result<T>,
        error: anyhow::Error,
    ) -> Result<T> {
        match result {
            Result::Ok(s) => {
                debug!("Converted as: {:?}", s);
                Ok(s)
            }
            Err(error_from_result) => {
                self.sender.send(error_from_result).await?;
                Err(error)
            }
        }
    }

    async fn post(&self, request: &LmsRequest) -> Result<LmsResponse> {
        debug!("Sending: {:?}", request);
        let response = self.client.post(&self.url).json(&request).send().await?;
        response
            .json()
            .await
            .map(|response| {
                debug!("Received: {:?}", response);
                response
            })
            .map_err(|error| error.into())
    }

    async fn post_no_result(&self, request: &LmsRequest) -> Result<()> {
        self.post(&request)
            .await
            .map(|_| ())
            .map_err(|error| error.into())
    }
}

/// The response sent by LMS is a JSON object with this structure. The actual payload is in the
/// result field.
#[derive(Clone, Debug, Deserialize)]
struct LmsResponse {
    #[allow(dead_code)]
    method: String,
    #[allow(dead_code)]
    params: (String, Vec<String>),

    result: serde_json::Value,
}

fn as_bool(response: LmsResponse, field: &String) -> Result<bool> {
    let value = result_field(response, field)?;
    match value {
        Value::Number(n) => n
            .as_i64()
            .map(|i| i != 0)
            .ok_or_else(|| anyhow!("{} is not an i64", n)),
        _ => bail!("Wrong top level type for bool: {:?}", value),
    }
}

fn as_u64(response: LmsResponse, field: &String) -> Result<u64> {
    let value = result_field(response, field)?;
    match value {
        Value::String(n) => n.parse::<u64>().map_err(|e| e.into()),
        Value::Number(n) => n.as_u64().ok_or_else(|| anyhow!("{} is not an u64", n)),
        _ => bail!("Wrong top level type for u64: {:?}", value),
    }
}

fn as_string(response: LmsResponse, field: &String) -> Result<String> {
    let value = result_field(response, field)?;
    match value {
        Value::String(s) => Ok(s.clone()),
        _ => bail!("Wrong top level type for string: {:?}", value),
    }
}

fn as_string_or_not_there(response: LmsResponse, field: &String) -> Result<Option<String>> {
    as_string(response, &field)
        .map(Some)
        .or_else(|e| match e.downcast_ref::<ResultError>() {
            Some(ResultError::NoField { .. }) => Ok(None),
            _ => Err(e),
        })
}

fn as_mode(response: LmsResponse, field: &String) -> Result<Mode> {
    let value = result_field(response, &field)?;
    match value {
        Value::String(s) => match s.as_str() {
            "stop" => Ok(Mode::Stop),
            "play" => Ok(Mode::Play),
            "pause" => Ok(Mode::Pause),
            other => bail!("Expected stop, play or pause, got {}", other),
        },
        _ => bail!("Wrong top level type for mode: {:?}", value),
    }
}

fn as_shuffle(response: LmsResponse, field: &String) -> Result<Shuffle> {
    fn wrong_value<T: std::fmt::Display>(value: T) -> anyhow::Error {
        anyhow!("Expected 0, 1 or 2, got {}", value)
    }

    let value = result_field(response, &field)?;
    match value {
        Value::String(s) => match s.as_str() {
            "0" => Ok(Shuffle::Off),
            "1" => Ok(Shuffle::Songs),
            "2" => Ok(Shuffle::Albums),
            _ => Err(wrong_value(s)),
        },
        Value::Number(n) => match n.as_u64() {
            Some(0) => Ok(Shuffle::Off),
            Some(1) => Ok(Shuffle::Songs),
            Some(2) => Ok(Shuffle::Albums),
            _ => Err(wrong_value(n)),
        },
        _ => bail!("Wrong top level type for shuffle: {:?}", value),
    }
}

#[derive(Debug, Error)]
enum ResultError {
    #[error("The result field has the wrong type: {response:?}")]
    ResultHasWrongType { response: LmsResponse },
    #[error("Unable to get field {field} in {response:?}")]
    NoField {
        response: LmsResponse,
        field: String,
    },
}

fn result_field(response: LmsResponse, field: &String) -> Result<Value> {
    let mut result = match response.result {
        Value::Object(ref map) => Ok(map.clone()),
        _ => Err(anyhow!(ResultError::ResultHasWrongType {
            response: response.clone()
        })),
    }?;
    result.remove(field).ok_or_else(|| {
        anyhow!(ResultError::NoField {
            response: response,
            field: field.clone()
        })
    })
}