mpdclient 0.2.0

Rust interface to MPD using libmpdclient
Documentation
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
use std::{borrow::BorrowMut, ffi::CString};

use mpdclient_sys::{
    mpd_connection_get_error, mpd_position_whence_MPD_POSITION_ABSOLUTE,
    mpd_position_whence_MPD_POSITION_AFTER_CURRENT,
    mpd_position_whence_MPD_POSITION_BEFORE_CURRENT, mpd_recv_queue_change_brief, mpd_run_add,
    mpd_run_add_id, mpd_run_add_id_whence, mpd_run_add_tag_id, mpd_run_add_whence, mpd_run_clear,
    mpd_run_clear_all_tags_id, mpd_run_clear_tag_id, mpd_run_delete, mpd_run_delete_id,
    mpd_run_delete_range, mpd_run_move, mpd_run_move_id, mpd_run_move_id_whence,
    mpd_run_move_range, mpd_run_move_range_whence, mpd_run_move_whence, mpd_run_prio,
    mpd_run_prio_id, mpd_run_prio_range, mpd_run_range_id, mpd_run_shuffle, mpd_run_shuffle_range,
    mpd_run_swap, mpd_run_swap_id, mpd_send_get_queue_song_id, mpd_send_get_queue_song_pos,
    mpd_send_list_queue_meta, mpd_send_list_queue_range_meta, mpd_send_queue_changes_brief,
    mpd_send_queue_changes_brief_range, mpd_send_queue_changes_meta,
    mpd_send_queue_changes_meta_range,
};

use crate::{
    Connection, Error, Tag,
    entity::{
        EntityReceiver,
        song::{Id, Song},
    },
    error::{MpdError, Result},
    i32_to_id,
};

/// Type of the queue version, used to prevent confusion.
pub type Version = u32;

/// Intermediate to bundle MPD queue functions.
///
/// All functions in this module refer to operations with and on the queue.
pub struct Queue<'a> {
    connection: &'a Connection,
}

impl<'a> Queue<'a> {
    pub(super) fn new(connection: &'a Connection) -> Self {
        Self { connection }
    }

    /// Returns a list of all songs in the queue with metadata.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn list(&self) -> Result<Vec<Song>> {
        self.connection
            .get_bool_error(|| unsafe { mpd_send_list_queue_meta(self.connection.connection()) })?;

        Song::extract_all(EntityReceiver::new(self.connection))
    }

    /// Returns a list of all songs within a range in the queue with metadata.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn list_range(&self, start: u32, end: Option<u32>) -> Result<Vec<Song>> {
        self.connection.get_bool_error(|| unsafe {
            mpd_send_list_queue_range_meta(
                self.connection.connection(),
                start,
                end.unwrap_or(u32::MAX),
            )
        })?;

        Song::extract_all(EntityReceiver::new(self.connection))
    }

    /// Returns the song at the position.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn get_song_pos(&self, position: u32) -> Result<Song> {
        self.connection.get_bool_error(|| unsafe {
            mpd_send_get_queue_song_pos(self.connection.connection(), position)
        })?;

        Song::extract_one(EntityReceiver::new(self.connection))
    }

    /// Returns the song with the id.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn get_song_id(&self, id: Id) -> Result<Song> {
        self.connection.get_bool_error(|| unsafe {
            mpd_send_get_queue_song_id(self.connection.connection(), id)
        })?;

        Song::extract_one(EntityReceiver::new(self.connection))
    }

    // --- CHANGES_META ---

    /// Returns a list of changes **with** metadata to the queue since `version`. The current
    /// version can be aquired with
    /// [`Status::queue_version()`](crate::connection::status::Status::queue_version()).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn changes_meta(&self, version: Version) -> Result<Vec<Song>> {
        self.connection.get_bool_error(|| unsafe {
            mpd_send_queue_changes_meta(self.connection.connection(), version)
        })?;

        Song::extract_all(EntityReceiver::new(self.connection))
    }

    /// Returns a list of changes **with** metadata to the queue in the range since `version`.
    ///
    /// The current version can be aquired with
    /// [`Status::queue_version()`](crate::connection::status::Status::queue_version()).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn changes_meta_range(
        &self,
        version: Version,
        start: u32,
        end: Option<u32>,
    ) -> Result<Vec<Song>> {
        self.connection.get_bool_error(|| unsafe {
            mpd_send_queue_changes_meta_range(
                self.connection.connection(),
                version,
                start,
                end.unwrap_or(u32::MAX),
            )
        })?;

        Song::extract_all(EntityReceiver::new(self.connection))
    }

    // --- CHANGES_BRIEF ---

    /// Returns an iterator [`ChangeIter`] of changes to the queue with minimally needed information
    /// since `version`.
    ///
    /// The current version can be aquired with
    /// [`Status::queue_version()`](crate::connection::status::Status::queue_version()).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn changes(&self, version: Version) -> Result<ChangeIter<'_>> {
        self.connection.get_bool_error(|| unsafe {
            mpd_send_queue_changes_brief(self.connection.connection(), version)
        })?;
        Ok(ChangeIter::new(self.connection))
    }

    /// Returns an iterator [`ChangeIter`] of changes to the queue with minimally needed information
    /// since `version` within a range.
    ///
    /// The current version can be aquired with
    /// [`Status::queue_version()`](crate::connection::status::Status::queue_version()).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn changes_range(
        &self,
        version: Version,
        start: u32,
        end: Option<u32>,
    ) -> Result<ChangeIter<'_>> {
        let end_u32 = end.unwrap_or(u32::MAX);
        self.connection.get_bool_error(|| unsafe {
            mpd_send_queue_changes_brief_range(
                self.connection.connection(),
                version,
                start,
                end_u32,
            )
        })?;

        Ok(ChangeIter::new(self.connection))
    }

    // --- Manipulation ---

    /// Add a song to the end of the queue.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn add(&self, uri: &str) -> Result<()> {
        let uri = CString::new(uri)?;
        self.connection
            .get_bool_error(|| unsafe { mpd_run_add(self.connection.connection(), uri.as_ptr()) })
    }

    /// Add a song to a specific position in the queue. `Whence` allows to also add relative to the
    /// currently playing song.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn add_position(&self, uri: &str, position: u32, whence: Position) -> Result<()> {
        let whence_u32 = u32::from(whence);
        let uri = CString::new(uri)?;
        self.connection.get_bool_error(|| unsafe {
            mpd_run_add_whence(
                self.connection.connection(),
                uri.as_ptr(),
                position,
                whence_u32,
            )
        })
    }

    fn get_id_error(&self, func: impl Fn() -> i32) -> Result<i32> {
        let ret = func();
        if ret == -1 {
            // unreachable!(), because error is ensured with ret == 0
            Err(Error::from_mpd(
                MpdError::from_sys(
                    unsafe { mpd_connection_get_error(self.connection.connection()) },
                    self.connection.connection(),
                )
                .unwrap_or_else(|| unreachable!()),
                self.connection.connection(),
            ))
        } else {
            Ok(ret)
        }
    }

    /// Add a song to the end of the queue returning the id of the song within the queue.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn add_id(&self, uri: &str) -> Result<Id> {
        let uri = CString::new(uri)?;
        Ok(i32_to_id(self.get_id_error(|| unsafe {
            mpd_run_add_id(self.connection.connection(), uri.as_ptr())
        })?))
    }

    /// Add a song to a specific position in the queue returning the id of the song within the
    /// queue. `Whence` allows to also add relative to the currently playing song.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn add_id_position(&self, uri: &str, position: u32, whence: Position) -> Result<Id> {
        let uri = CString::new(uri)?;
        let whence_u32 = u32::from(whence);
        Ok(i32_to_id(self.get_id_error(|| unsafe {
            mpd_run_add_id_whence(
                self.connection.connection(),
                uri.as_ptr(),
                position,
                whence_u32,
            )
        })?))
    }

    /// Delete a song in the `position`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn delete(&self, position: u32) -> Result<()> {
        self.connection
            .get_bool_error(|| unsafe { mpd_run_delete(self.connection.connection(), position) })
    }

    /// Delete multiple songs in the range of positions.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn delete_range(&self, start: u32, end: Option<u32>) -> Result<()> {
        self.connection.get_bool_error(|| unsafe {
            mpd_run_delete_range(self.connection.connection(), start, end.unwrap_or(u32::MAX))
        })
    }

    /// Delete the song with the `id` withing the queue.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn delete_id(&self, id: Id) -> Result<()> {
        self.connection
            .get_bool_error(|| unsafe { mpd_run_delete_id(self.connection.connection(), id) })
    }

    /// Shuffles the queue.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn shuffle(&self) -> Result<()> {
        self.connection
            .get_bool_error(|| unsafe { mpd_run_shuffle(self.connection.connection()) })
    }

    /// Shuffles the queue within a range.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn shuffle_range(&self, start: u32, end: Option<u32>) -> Result<()> {
        self.connection.get_bool_error(|| unsafe {
            mpd_run_shuffle_range(self.connection.connection(), start, end.unwrap_or(u32::MAX))
        })
    }

    /// Completely clears the queue.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn clear(&self) -> Result<()> {
        self.connection
            .get_bool_error(|| unsafe { mpd_run_clear(self.connection.connection()) })
    }

    /// Moves a song `from` one position `to` another.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn move_pos(&self, from: u32, to: u32) -> Result<()> {
        self.connection
            .get_bool_error(|| unsafe { mpd_run_move(self.connection.connection(), from, to) })
    }

    /// Moves a song `from` one position `to` another, allowing moving relative to the currently
    /// playing song.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn move_whence(&self, from: u32, to: u32, whence: Position) -> Result<()> {
        let whence_u32 = u32::from(whence);
        self.connection.get_bool_error(|| unsafe {
            mpd_run_move_whence(self.connection.connection(), from, to, whence_u32)
        })
    }

    /// Moves a song with the `id` `to` a position.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn move_id(&self, id: Id, to: u32) -> Result<()> {
        self.connection
            .get_bool_error(|| unsafe { mpd_run_move_id(self.connection.connection(), id, to) })
    }

    /// Moves a song with the `id` `to` a position, allowing moving relative to the currently
    /// playing song.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn move_id_whence(&self, id: Id, to: u32, whence: Position) -> Result<()> {
        let whence_u32 = u32::from(whence);
        self.connection.get_bool_error(|| unsafe {
            mpd_run_move_id_whence(self.connection.connection(), id, to, whence_u32)
        })
    }

    /// Moves a range of songs `to` a position.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn move_range(&self, start: u32, end: u32, to: u32) -> Result<()> {
        self.connection.get_bool_error(|| unsafe {
            mpd_run_move_range(self.connection.connection(), start, end, to)
        })
    }

    /// Moves a range of songs `to` a position, allowing moving relative to the currently
    /// playing song.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn move_range_whence(&self, start: u32, end: u32, to: u32, whence: Position) -> Result<()> {
        let whence_u32 = u32::from(whence);
        self.connection.get_bool_error(|| unsafe {
            mpd_run_move_range_whence(self.connection.connection(), start, end, to, whence_u32)
        })
    }

    /// Swaps a song in the queue with another, labelled by position.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn swap(&self, one: u32, two: u32) -> Result<()> {
        self.connection
            .get_bool_error(|| unsafe { mpd_run_swap(self.connection.connection(), one, two) })
    }

    /// Swaps a song in the queue with another, labelled by id.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn swap_id(&self, id_one: Id, id_two: Id) -> Result<()> {
        self.connection.get_bool_error(|| unsafe {
            mpd_run_swap_id(self.connection.connection(), id_one, id_two)
        })
    }

    /// Adds a non persistent [`Tag`] to a song. Only possible with remote songs.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn add_tag_id(&self, id: Id, tag: Tag, value: &str) -> Result<()> {
        let value = CString::new(value)?;
        self.connection.get_bool_error(|| unsafe {
            mpd_run_add_tag_id(self.connection.connection(), id, tag as i32, value.as_ptr())
        })
    }

    /// Clears a [`Tag`] from a song. Only possible with remote songs.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn clear_tag_id(&self, id: Id, tag: Tag) -> Result<()> {
        self.connection.get_bool_error(|| unsafe {
            mpd_run_clear_tag_id(self.connection.connection(), id, tag as i32)
        })
    }

    /// Clears all [`Tag`]s from a song. Only possible with remote songs.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn clear_all_tags_id(&self, id: Id) -> Result<()> {
        self.connection.get_bool_error(|| unsafe {
            mpd_run_clear_all_tags_id(self.connection.connection(), id)
        })
    }

    /// Change the priority withing the queue of a specified song in the `position`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn priority(&self, priority: u32, position: u32) -> Result<()> {
        self.connection.get_bool_error(|| unsafe {
            mpd_run_prio(self.connection.connection(), priority, position)
        })
    }

    /// Change the priority of multiple songs withing a range in the queue.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn priority_range(&self, priority: u32, start: u32, end: Option<u32>) -> Result<()> {
        self.connection.get_bool_error(|| unsafe {
            mpd_run_prio_range(
                self.connection.connection(),
                priority,
                start,
                end.unwrap_or(u32::MAX),
            )
        })
    }

    /// Change the priority withing the queue of a specified song with the `id`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn priority_id(&self, priority: u32, id: Id) -> Result<()> {
        self.connection.get_bool_error(|| unsafe {
            mpd_run_prio_id(self.connection.connection(), priority, id)
        })
    }

    /// Sets the part of a song that should be played, identified by `id`. Cannot be the currently
    /// playing song.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`] if MPD returns an error.
    pub fn range_id(&self, id: Id, start: f32, end: Option<f32>) -> Result<()> {
        self.connection.get_bool_error(|| unsafe {
            mpd_run_range_id(self.connection.connection(), id, start, end.unwrap_or(-1.0))
        })
    }
}

// --- Position ---
/// Position in which a song should be added to the queue.
#[allow(clippy::cast_possible_wrap)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Position {
    /// Absolute position within the queue
    Absolute = mpd_position_whence_MPD_POSITION_ABSOLUTE as isize,

    /// Relative to after the current song within the queue.
    AfterCurrent = mpd_position_whence_MPD_POSITION_AFTER_CURRENT as isize,

    /// Relative to before the current song within the queue.
    BeforeCurrent = mpd_position_whence_MPD_POSITION_BEFORE_CURRENT as isize,
}

impl From<Position> for u32 {
    fn from(value: Position) -> Self {
        match value {
            Position::Absolute => mpd_position_whence_MPD_POSITION_ABSOLUTE,
            Position::AfterCurrent => mpd_position_whence_MPD_POSITION_AFTER_CURRENT,
            Position::BeforeCurrent => mpd_position_whence_MPD_POSITION_BEFORE_CURRENT,
        }
    }
}

// --- Change ---

/// A brief item describing a queue change
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Change {
    /// Position of the changed song
    pub position: u32,

    /// Id of the changed song
    pub id: Id,
}

/// Iterator to get brief queue changes ready to be received from MPD.
#[derive(Debug)]
pub struct ChangeIter<'a> {
    connection: &'a Connection,
}

impl<'a> ChangeIter<'a> {
    pub(super) fn new(connection: &'a Connection) -> Self {
        Self { connection }
    }
}

impl Iterator for ChangeIter<'_> {
    type Item = Change;

    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            let mut position = 0;
            let mut id = 0;
            let change = mpd_recv_queue_change_brief(
                self.connection.connection(),
                position.borrow_mut(),
                id.borrow_mut(),
            );
            if change {
                Some(Change { position, id })
            } else {
                None
            }
        }
    }
}