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
use std::ffi::CString;

use mpdclient_sys::{
    mpd_count_db_songs, mpd_operator_MPD_OPERATOR_DEFAULT, mpd_response_finish,
    mpd_search_add_any_tag_constraint, mpd_search_add_base_constraint, mpd_search_add_db_songs,
    mpd_search_add_db_songs_to_playlist, mpd_search_add_expression,
    mpd_search_add_modified_since_constraint, mpd_search_add_position, mpd_search_add_sort_name,
    mpd_search_add_sort_tag, mpd_search_add_tag_constraint, mpd_search_add_uri_constraint,
    mpd_search_add_window, mpd_search_commit, mpd_search_db_songs, mpd_search_db_tags,
    mpd_search_queue_songs, mpd_searchcount_db_songs,
};

#[cfg(feature = "protocol_0_24")]
use mpdclient_sys::mpd_search_add_added_since_constraint;
const DEF_OP: u32 = mpd_operator_MPD_OPERATOR_DEFAULT;

use crate::{
    Tag,
    entity::{EntityReceiver, Song},
    error::Result,
};

use super::{Connection, Position, stats::Stats};

/// Intermediate to bundle MPD search functions.
pub struct Search<'a> {
    connection: &'a Connection,
}

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

    /// Searches through the database of the MPD.
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    pub fn database(&self, exact: bool) -> Result<SongConstraints<'_>> {
        self.connection.get_bool_error(|| unsafe {
            mpd_search_db_songs(self.connection.connection(), exact)
        })?;
        Ok(SongConstraints {
            connection: self.connection,
        })
    }

    /// Searches through the database of the MPD and adds the results to the queue.
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    pub fn database_add(&self, exact: bool) -> Result<AddConstraint<'_>> {
        self.connection.get_bool_error(|| unsafe {
            mpd_search_add_db_songs(self.connection.connection(), exact)
        })?;
        Ok(AddConstraint {
            connection: self.connection,
        })
    }

    /// Searches through the database of the MPD and adds the results to a playlist.
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    pub fn database_add_playlist(&self, name: &str) -> Result<AddConstraint<'_>> {
        let cname = CString::new(name)?;
        self.connection.get_bool_error(|| unsafe {
            mpd_search_add_db_songs_to_playlist(self.connection.connection(), cname.as_ptr())
        })?;
        Ok(AddConstraint {
            connection: self.connection,
        })
    }

    /// Searches through the current queue.
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    pub fn queue(&self, exact: bool) -> Result<SongConstraints<'_>> {
        self.connection.get_bool_error(|| unsafe {
            mpd_search_queue_songs(self.connection.connection(), exact)
        })?;
        Ok(SongConstraints {
            connection: self.connection,
        })
    }

    /// Searches through a tag on every song in the database.
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    pub fn tags(&self, tag: Tag) -> Result<TagConstraints<'_>> {
        self.connection.get_bool_error(|| unsafe {
            mpd_search_db_tags(self.connection.connection(), tag as i32)
        })?;
        println!("Tags");
        Ok(TagConstraints {
            connection: self.connection,
            tag,
        })
    }

    /// Returns statistics on songs in the database.
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    pub fn count_database(&self) -> Result<StatsConstraints<'_>> {
        self.connection
            .get_bool_error(|| unsafe { mpd_count_db_songs(self.connection.connection()) })?;
        Ok(StatsConstraints {
            connection: self.connection,
        })
    }

    /// Returns statistics on songs in the database with a case insensitive search.
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    pub fn count_database_i(&self) -> Result<StatsConstraints<'_>> {
        self.connection
            .get_bool_error(|| unsafe { mpd_searchcount_db_songs(self.connection.connection()) })?;
        Ok(StatsConstraints {
            connection: self.connection,
        })
    }
}

// --- Constraint ---

/// Constraint to [search](Search) in.
pub trait Constraint<'a> {
    /// Expected return type from the commit.
    type Commit;

    /// Trait access to the [`Connection`] stored in the implementing structs.
    fn connection(&self) -> &'a Connection;

    /// Needs to commit the search and get the correct return type from MPD.
    ///
    /// # Errors
    ///
    /// Usually returns [`Error::Mpd`](crate::error::Error::Mpd)  if MPD returns an error.
    fn commit(&self) -> Result<Self::Commit>;

    /// Sets the base directory within the MPD database in which to search.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    fn base(&self, dir: &str) -> Result<&Self> {
        let cdir = CString::new(dir)?;
        self.connection().get_bool_error(|| unsafe {
            mpd_search_add_base_constraint(self.connection().connection(), DEF_OP, cdir.as_ptr())
        })?;
        Ok(self)
    }

    /// Sets the uri within the MPD database that should be searched.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    fn uri(&self, uri: &str) -> Result<&Self> {
        let curi = CString::new(uri)?;
        self.connection().get_bool_error(|| unsafe {
            mpd_search_add_uri_constraint(self.connection().connection(), DEF_OP, curi.as_ptr())
        })?;
        Ok(self)
    }

    /// Sets the value for a tag within a song that should be searched.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    fn tag(&self, tag: Tag, value: &str) -> Result<&Self> {
        let cvalue = CString::new(value)?;
        self.connection().get_bool_error(|| unsafe {
            mpd_search_add_tag_constraint(
                self.connection().connection(),
                DEF_OP,
                tag as i32,
                cvalue.as_ptr(),
            )
        })?;
        Ok(self)
    }

    /// Sets the value for any tag within a song that should be searched.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    fn any_tag(&self, value: &str) -> Result<&Self> {
        let cvalue = CString::new(value)?;
        self.connection().get_bool_error(|| unsafe {
            mpd_search_add_any_tag_constraint(
                self.connection().connection(),
                DEF_OP,
                cvalue.as_ptr(),
            )
        })?;
        Ok(self)
    }

    /// Sets the search to all entities modified since `time`.
    ///
    /// `time` is entered in the `UNIX_TIMESTAMP`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    // allow because it should be just accepted by the c code
    #[allow(clippy::cast_possible_wrap)]
    fn modified_since(&self, time: u64) -> Result<&Self> {
        self.connection().get_bool_error(|| unsafe {
            mpd_search_add_modified_since_constraint(
                self.connection().connection(),
                DEF_OP,
                time as i64,
            )
        })?;
        Ok(self)
    }

    /// Sets the search to all entities added since `time` to the database.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    #[cfg(feature = "protocol_0_24")]
    // allow because it should be just accepted by the c code
    #[allow(clippy::cast_possible_wrap)]
    fn added_since(&self, time: u64) -> Result<&Self> {
        self.connection().get_bool_error(|| unsafe {
            mpd_search_add_added_since_constraint(
                self.connection().connection(),
                DEF_OP,
                time as i64,
            )
        })?;
        Ok(self)
    }

    /// Sets the search to a expression term.
    ///
    /// An expression may look like: `"((artist == "Kraftwerk") AND (title == "Metall auf
    /// Metall"))"`. Further information in the
    /// [MPD protocol documentation](https://mpd.readthedocs.io/en/latest/protocol.html#filters)
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    fn expression(&self, value: &str) -> Result<&Self> {
        let cvalue = CString::new(value)?;
        self.connection().get_bool_error(|| unsafe {
            mpd_search_add_expression(self.connection().connection(), cvalue.as_ptr())
        })?;
        Ok(self)
    }

    // --- Grouping/Sorting ---

    // Doesnt get accepted by the server
    // /// Group the results by a tag.
    // ///
    // /// # Errors
    // ///
    // /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    // fn group_tag(&self, tag: Tag) -> Result<&Self> {
    //     self.connection().get_bool_error(|| unsafe {
    //         mpd_search_add_group_tag(self.connection().connection(), tag as i32)
    //     })?;
    //     Ok(self)
    // }

    /// Sort the results by a named attribute. Can either be a [`Tag`] or `"Last-Modified"`.
    /// The `String` representation of a [`Tag`] can be aquired through [`Tag::name()`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    fn sort_name(&self, name: &str, descending: bool) -> Result<&Self> {
        let cname = CString::new(name)?;
        self.connection().get_bool_error(|| unsafe {
            mpd_search_add_sort_name(self.connection().connection(), cname.as_ptr(), descending)
        })?;
        Ok(self)
    }

    /// Sort the results by a tag.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    fn sort_tag(&self, tag: Tag, descending: bool) -> Result<&Self> {
        self.connection().get_bool_error(|| unsafe {
            mpd_search_add_sort_tag(self.connection().connection(), tag as i32, descending)
        })?;
        Ok(self)
    }

    /// Requests only a part of the whole result.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    fn window(&self, start: u32, end: u32) -> Result<&Self> {
        self.connection().get_bool_error(|| unsafe {
            mpd_search_add_window(self.connection().connection(), start, end)
        })?;
        Ok(self)
    }
}

/// Constraint used when the search immediatly adds results to a playlist.
pub struct AddConstraint<'a> {
    connection: &'a Connection,
}

impl<'a> Constraint<'a> for AddConstraint<'a> {
    type Commit = ();

    fn connection(&self) -> &'a Connection {
        self.connection
    }

    fn commit(&self) -> Result<Self::Commit> {
        self.connection()
            .get_bool_error(|| unsafe { mpd_search_commit(self.connection().connection()) })?;
        self.connection()
            .get_bool_error(|| unsafe { mpd_response_finish(self.connection().connection()) })?;
        Ok(())
    }
}

impl AddConstraint<'_> {
    /// Adds the results to a specific position in the queue or a playlist.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    pub fn add_position(&self, position: u32, whence: Position) -> Result<&Self> {
        self.connection().get_bool_error(|| unsafe {
            mpd_search_add_position(self.connection().connection(), position, whence as u32)
        })?;
        Ok(self)
    }
}

/// Constraint used when the search returns a list of [`Song`]s.
pub struct SongConstraints<'a> {
    connection: &'a Connection,
}

impl<'a> Constraint<'a> for SongConstraints<'a> {
    type Commit = Vec<Song>;

    fn connection(&self) -> &'a Connection {
        self.connection
    }

    fn commit(&self) -> Result<Self::Commit> {
        self.connection
            .get_bool_error(|| unsafe { mpd_search_commit(self.connection.connection()) })?;
        Song::extract_all(EntityReceiver::new(self.connection))
    }
}

/// Constraint used when the search returns stats about the database.
pub struct StatsConstraints<'a> {
    connection: &'a Connection,
}

impl<'a> Constraint<'a> for StatsConstraints<'a> {
    type Commit = Stats;

    fn connection(&self) -> &'a Connection {
        self.connection
    }

    fn commit(&self) -> Result<Self::Commit> {
        self.connection
            .get_bool_error(|| unsafe { mpd_search_commit(self.connection.connection()) })?;
        Stats::receive(self.connection)
    }
}

/// Constraint used when the search returns tag values.
pub struct TagConstraints<'a> {
    connection: &'a Connection,
    tag: Tag,
}

impl<'a> Constraint<'a> for TagConstraints<'a> {
    type Commit = TagReceiver<'a>;

    fn connection(&self) -> &'a Connection {
        self.connection
    }

    fn commit(&self) -> Result<Self::Commit> {
        self.connection
            .get_bool_error(|| unsafe { mpd_search_commit(self.connection.connection()) })?;

        Ok(TagReceiver::new(self.connection, self.tag))
    }
}

/// Describing a tag returned by searching with [`Search::tags()`].
pub struct TagReceiver<'a> {
    connection: &'a Connection,
    tag: Tag,
}

impl<'a> TagReceiver<'a> {
    pub(super) fn new(connection: &'a Connection, tag: Tag) -> Self {
        Self { connection, tag }
    }

    /// Shortcut to collect all tag values
    ///
    /// # Errors
    ///
    /// Returns [`Error::Mpd`](crate::Error::Mpd) if MPD returns an error.
    pub fn receive_all(self) -> Result<Vec<String>> {
        self.collect()
    }
}

impl Iterator for TagReceiver<'_> {
    type Item = Result<String>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.tag.receive(self.connection) {
            Ok(val) => val.map(Ok),
            Err(err) => Some(Err(err)),
        }
    }
}