koan-core 0.59.0

Core library for koan — bit-perfect music player. Audio engine, player, database, format strings.
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
//! The library's shelves: favourites, recently played, what is downloaded and
//! a search. Each is
//! one narrowing, applied alike to the album, artist and track listings, so a
//! shelf is not a list of its own but the library's own listings with a filter
//! on. A shelf page shows the first few of each (`summary`), and its "See all"
//! opens the same listing with the same filter: the two read one query, so
//! they cannot disagree about what is on the shelf or in what order.
//!
//! What each shelf holds, how far back it reaches and how it is ordered is
//! decided here and nowhere else. Every front end asks for a shelf by name.
//!
//! Adding a shelf means a variant of [`Shelf`] and its
//! narrowing in each of [`Shelf::albums`], [`Shelf::artists`] and
//! [`Shelf::tracks`]; the summary and every listing follow from those.

use crate::db::connection::DbError;
use crate::db::queries::{
    self, AlbumFilter, AlbumOrder, AlbumQuery, AlbumRow, ArtistOrder, ArtistQuery, ArtistRow,
    PlayedSince, TrackFilter, TrackOrder, TrackRow,
};

/// How far back Recently played reaches.
pub const RECENT_DAYS: i64 = 30;

/// How many of each a shelf page shows before "See all": a cloud of artists,
/// about one row of records, a short list of tracks.
pub const PREVIEW_ARTISTS: u32 = 12;
pub const PREVIEW_ALBUMS: u32 = 8;
pub const PREVIEW_TRACKS: u32 = 10;

/// The clock the shelves read, in unix seconds.
pub fn now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs() as i64)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shelf<'a> {
    /// What the account has favourited.
    Favourites,
    /// What the account played in the last `RECENT_DAYS`, the most recently
    /// played first, each once.
    Recent,
    /// What matches `q`: names for records and artists, the full-text index
    /// for tracks.
    Search(&'a str),
    /// What can play on this device, downloaded or in the library. Records
    /// count with any track here, fully there first, and each carries how
    /// much of it is.
    Downloaded,
}

impl<'a> Shelf<'a> {
    /// The shelf's records, for `user` at `now`. Page it with `limit` and
    /// `offset`; narrow it further with the album browser's own filters.
    pub fn albums(self, user: i64, now: i64) -> AlbumQuery<'a> {
        match self {
            Shelf::Favourites => AlbumQuery {
                favourites_of: Some(user),
                order: AlbumOrder::ArtistThenDate,
                ..Default::default()
            },
            Shelf::Recent => AlbumQuery {
                played: Some(recent(user, now)),
                order: AlbumOrder::LastPlayed,
                ..Default::default()
            },
            Shelf::Search(q) => AlbumQuery {
                search: Some(q),
                order: AlbumOrder::RecentlyAdded,
                ..Default::default()
            },
            Shelf::Downloaded => AlbumQuery {
                filter: AlbumFilter {
                    on_device: true,
                    ..Default::default()
                },
                order: AlbumOrder::Downloaded,
                ..Default::default()
            },
        }
    }

    /// The shelf's artists: album artists, as the artist browser lists them.
    pub fn artists(self, user: i64, now: i64) -> ArtistQuery<'a> {
        match self {
            Shelf::Favourites => ArtistQuery {
                favourites_of: Some(user),
                order: ArtistOrder::Name,
                ..Default::default()
            },
            Shelf::Recent => ArtistQuery {
                played: Some(recent(user, now)),
                order: ArtistOrder::LastPlayed,
                ..Default::default()
            },
            Shelf::Search(q) => ArtistQuery {
                search: Some(q),
                order: ArtistOrder::Name,
                ..Default::default()
            },
            Shelf::Downloaded => ArtistQuery {
                filter: AlbumFilter {
                    on_device: true,
                    ..Default::default()
                },
                order: ArtistOrder::Name,
                ..Default::default()
            },
        }
    }

    /// The shelf's tracks, and the order they read in (`descending` as
    /// `filter_tracks` takes it).
    pub fn tracks(self, user: i64, now: i64) -> Tracks {
        match self {
            Shelf::Favourites => Tracks {
                filter: TrackFilter {
                    favourites_of: Some(user),
                    ..Default::default()
                },
                order: TrackOrder::ArtistAlbumDiscTrack,
                descending: false,
            },
            Shelf::Recent => Tracks {
                filter: TrackFilter {
                    played: Some(recent(user, now)),
                    ..Default::default()
                },
                order: TrackOrder::LastPlayed,
                descending: true,
            },
            Shelf::Search(q) => Tracks {
                filter: TrackFilter {
                    search: Some(q.to_owned()),
                    ..Default::default()
                },
                order: TrackOrder::ArtistAlbumDiscTrack,
                descending: false,
            },
            Shelf::Downloaded => Tracks {
                filter: TrackFilter {
                    on_device: true,
                    ..Default::default()
                },
                order: TrackOrder::ArtistAlbumDiscTrack,
                descending: false,
            },
        }
    }
}

fn recent(user: i64, now: i64) -> PlayedSince {
    PlayedSince {
        user,
        since: now - RECENT_DAYS * 24 * 60 * 60,
    }
}

/// A shelf's tracks: the filter, and the order they read in.
#[derive(Debug, Clone)]
pub struct Tracks {
    pub filter: TrackFilter,
    pub order: TrackOrder,
    pub descending: bool,
}

impl Tracks {
    pub fn page(
        &self,
        conn: &rusqlite::Connection,
        limit: u32,
        offset: u32,
    ) -> Result<Vec<TrackRow>, DbError> {
        queries::filter_tracks(
            conn,
            &self.filter,
            self.order,
            self.descending,
            limit,
            offset,
        )
    }

    pub fn count(&self, conn: &rusqlite::Connection) -> Result<u64, DbError> {
        queries::count_tracks(conn, &self.filter)
    }
}

/// The first few of one kind on a shelf, and how many there are in all.
#[derive(Debug, Clone)]
pub struct Section<T> {
    pub preview: Vec<T>,
    pub total: u64,
}

/// A shelf page: the first few artists, records and tracks, with their totals.
#[derive(Debug, Clone)]
pub struct Summary {
    pub artists: Section<ArtistRow>,
    pub albums: Section<AlbumRow>,
    pub tracks: Section<TrackRow>,
}

impl Summary {
    pub fn is_empty(&self) -> bool {
        self.artists.total == 0 && self.albums.total == 0 && self.tracks.total == 0
    }
}

/// What a shelf page shows: the head of each of the shelf's listings, narrowed
/// to what can play here when `on_device` (offline).
pub fn summary(
    conn: &rusqlite::Connection,
    shelf: Shelf,
    user: i64,
    now: i64,
    on_device: bool,
) -> Result<Summary, DbError> {
    let mut artists = shelf.artists(user, now);
    let mut albums = shelf.albums(user, now);
    let mut tracks = shelf.tracks(user, now);
    artists.filter.on_device |= on_device;
    albums.filter.on_device |= on_device;
    tracks.filter.on_device |= on_device;
    Ok(Summary {
        artists: Section {
            preview: queries::list_artists(
                conn,
                &ArtistQuery {
                    limit: Some(PREVIEW_ARTISTS),
                    without_track_counts: true,
                    ..artists
                },
            )?,
            total: queries::count_artists(conn, &artists)?,
        },
        albums: Section {
            preview: queries::list_albums(
                conn,
                &AlbumQuery {
                    limit: Some(PREVIEW_ALBUMS),
                    ..albums
                },
            )?,
            total: queries::count_albums(conn, &albums)?,
        },
        tracks: Section {
            preview: tracks.page(conn, PREVIEW_TRACKS, 0)?,
            total: tracks.count(conn)?,
        },
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::connection::Database;
    use crate::db::queries::{
        add_favourite, record_play_at, sample_meta, set_favourite_album, set_favourite_artist,
        upsert_track,
    };

    const NOW: i64 = 1_800_000_000;
    const DAY: i64 = 24 * 60 * 60;

    fn db() -> Database {
        let conn = rusqlite::Connection::open_in_memory().unwrap();
        conn.pragma_update(None, "foreign_keys", "on").unwrap();
        crate::db::schema::create_tables(&conn).unwrap();
        Database { conn }
    }

    /// Three records by three artists, two tracks each. Returns the tracks.
    fn library(db: &Database) -> Vec<TrackRow> {
        for (artist, album) in [("Ayla", "Moss"), ("Bryn", "Tide"), ("Cato", "Ember")] {
            for (n, title) in ["One", "Two"].iter().enumerate() {
                let mut m = sample_meta(&format!("{album} {title}"), artist, album);
                m.track_number = Some(n as i32 + 1);
                upsert_track(&db.conn, &m).unwrap();
            }
        }
        queries::filter_tracks(
            &db.conn,
            &TrackFilter::default(),
            TrackOrder::Title,
            false,
            100,
            0,
        )
        .unwrap()
    }

    fn by_title<'a>(tracks: &'a [TrackRow], title: &str) -> &'a TrackRow {
        tracks.iter().find(|t| t.title == title).unwrap()
    }

    #[test]
    fn recently_played_is_the_window_newest_first_each_once() {
        let db = db();
        let tracks = library(&db);
        let user = queries::LOCAL_USER;
        let play = |title: &str, ago: i64| {
            record_play_at(
                &db.conn,
                user,
                by_title(&tracks, title).id,
                NOW - ago,
                None,
                "t",
            )
            .unwrap();
        };
        play("Moss One", 3 * DAY);
        play("Tide Two", 2 * DAY);
        play("Moss Two", DAY);
        play("Moss One", 60);
        play("Ember One", 40 * DAY);

        let s = summary(&db.conn, Shelf::Recent, user, NOW, false).unwrap();
        let titles: Vec<_> = s.tracks.preview.iter().map(|t| t.title.as_str()).collect();
        assert_eq!(
            titles,
            ["Moss One", "Moss Two", "Tide Two"],
            "newest play first, once each"
        );
        assert_eq!(
            s.tracks.total, 3,
            "the play from 40 days ago is outside the window"
        );
        let albums: Vec<_> = s.albums.preview.iter().map(|a| a.title.as_str()).collect();
        assert_eq!(albums, ["Moss", "Tide"]);
        let artists: Vec<_> = s.artists.preview.iter().map(|a| a.name.as_str()).collect();
        assert_eq!(artists, ["Ayla", "Bryn"]);
        assert_eq!((s.albums.total, s.artists.total), (2, 2));
    }

    #[test]
    fn favourites_are_the_accounts_own() {
        let db = db();
        let tracks = library(&db);
        let user = queries::LOCAL_USER;
        let moss = by_title(&tracks, "Moss One");
        add_favourite(&db.conn, user, by_title(&tracks, "Tide Two").id).unwrap();
        add_favourite(&db.conn, user, moss.id).unwrap();
        set_favourite_album(&db.conn, user, moss.album_id.unwrap(), true).unwrap();
        set_favourite_artist(&db.conn, user, moss.artist_id.unwrap(), true).unwrap();

        let s = summary(&db.conn, Shelf::Favourites, user, NOW, false).unwrap();
        let titles: Vec<_> = s.tracks.preview.iter().map(|t| t.title.as_str()).collect();
        assert_eq!(titles, ["Moss One", "Tide Two"], "by artist, then record");
        assert_eq!(s.albums.preview.len(), 1);
        assert_eq!(s.artists.preview[0].name, "Ayla");
        assert_eq!((s.tracks.total, s.albums.total, s.artists.total), (2, 1, 1));
    }

    #[test]
    fn a_search_shelf_narrows_each_listing_by_the_query() {
        let db = db();
        library(&db);
        let s = summary(
            &db.conn,
            Shelf::Search("tide"),
            queries::LOCAL_USER,
            NOW,
            false,
        )
        .unwrap();
        assert_eq!(s.albums.preview[0].title, "Tide");
        assert_eq!(s.tracks.total, 2);
        assert!(s.artists.preview.is_empty(), "no artist is called tide");
    }

    #[test]
    fn downloaded_is_what_can_play_here_fully_there_first() {
        let db = db();
        library(&db);
        db.conn
            .execute("UPDATE tracks SET path = NULL", [])
            .unwrap();
        db.conn
            .execute(
                "UPDATE tracks SET cached_path = '/cache/' || title
                  WHERE title IN ('Moss One', 'Tide One', 'Tide Two')",
                [],
            )
            .unwrap();
        let s = summary(&db.conn, Shelf::Downloaded, queries::LOCAL_USER, NOW, false).unwrap();
        let albums: Vec<_> = s
            .albums
            .preview
            .iter()
            .map(|a| (a.title.as_str(), a.on_device.map(|d| (d.have, d.total))))
            .collect();
        assert_eq!(albums, [("Tide", Some((2, 2))), ("Moss", Some((1, 2)))]);
        let artists: Vec<_> = s.artists.preview.iter().map(|a| a.name.as_str()).collect();
        assert_eq!(artists, ["Ayla", "Bryn"]);
        assert_eq!(s.tracks.total, 3);
    }

    #[test]
    fn a_preview_is_the_head_of_the_listing_its_total_counts() {
        let db = db();
        let tracks = library(&db);
        let user = queries::LOCAL_USER;
        for (i, t) in tracks.iter().enumerate() {
            add_favourite(&db.conn, user, t.id).unwrap();
            record_play_at(&db.conn, user, t.id, NOW - i as i64 * 60, None, "t").unwrap();
        }
        for shelf in [Shelf::Favourites, Shelf::Recent, Shelf::Downloaded] {
            let t = shelf.tracks(user, NOW);
            let all = t.page(&db.conn, 1000, 0).unwrap();
            let s = summary(&db.conn, shelf, user, NOW, false).unwrap();
            assert_eq!(s.tracks.total, all.len() as u64, "{shelf:?}");
            assert_eq!(
                s.tracks.preview.iter().map(|t| t.id).collect::<Vec<_>>(),
                all.iter()
                    .take(PREVIEW_TRACKS as usize)
                    .map(|t| t.id)
                    .collect::<Vec<_>>(),
                "{shelf:?}: the preview is the listing's head"
            );
            let albums = queries::list_albums(&db.conn, &shelf.albums(user, NOW)).unwrap();
            assert_eq!(s.albums.total, albums.len() as u64);
            assert_eq!(
                s.albums.preview.iter().map(|a| a.id).collect::<Vec<_>>(),
                albums
                    .iter()
                    .take(PREVIEW_ALBUMS as usize)
                    .map(|a| a.id)
                    .collect::<Vec<_>>()
            );
        }
    }
}