mecomp_daemon/services/
mod.rs

1use log::warn;
2use mecomp_storage::{
3    db::schemas::{
4        album::{Album, TABLE_NAME as ALBUM_TABLE_NAME},
5        artist::{Artist, TABLE_NAME as ARTIST_TABLE_NAME},
6        collection::{Collection, TABLE_NAME as COLLECTION_TABLE_NAME},
7        dynamic::{DynamicPlaylist, TABLE_NAME as DYNAMIC_PLAYLIST_TABLE_NAME},
8        playlist::{Playlist, TABLE_NAME as PLAYLIST_TABLE_NAME},
9        song::{Song, TABLE_NAME as SONG_TABLE_NAME},
10        Thing,
11    },
12    errors::{Error, StorageResult},
13};
14use one_or_many::OneOrMany;
15use surrealdb::{Connection, Surreal};
16
17pub mod library;
18#[cfg(feature = "analysis")]
19pub mod radio;
20
21/// Get the songs associated with every thing in the list.
22///
23/// This function will go through the list of things and get the songs associated with each thing.
24///
25/// It will then remove duplicates from the list of songs.
26///
27/// # Errors
28///
29/// This function will return an error if there is an issue reading the songs from the database.
30pub async fn get_songs_from_things<C: Connection>(
31    db: &Surreal<C>,
32    things: &[Thing],
33) -> StorageResult<OneOrMany<Song>> {
34    // go through the list, and get songs for each thing (depending on what it is)
35    let mut songs: OneOrMany<Song> = OneOrMany::None;
36    for thing in things {
37        match thing.tb.as_str() {
38            ALBUM_TABLE_NAME => {
39                for song in Album::read_songs(db, thing.clone().into()).await? {
40                    songs.push(song);
41                }
42            }
43            ARTIST_TABLE_NAME => {
44                for song in Artist::read_songs(db, thing.clone().into()).await? {
45                    songs.push(song);
46                }
47            }
48            COLLECTION_TABLE_NAME => {
49                for song in Collection::read_songs(db, thing.clone().into()).await? {
50                    songs.push(song);
51                }
52            }
53            PLAYLIST_TABLE_NAME => {
54                for song in Playlist::read_songs(db, thing.clone().into()).await? {
55                    songs.push(song);
56                }
57            }
58            SONG_TABLE_NAME => songs.push(
59                Song::read(db, thing.clone().into())
60                    .await?
61                    .ok_or(Error::NotFound)?,
62            ),
63            DYNAMIC_PLAYLIST_TABLE_NAME => {
64                for song in DynamicPlaylist::run_query_by_id(db, thing.clone().into())
65                    .await?
66                    .unwrap_or_default()
67                {
68                    songs.push(song);
69                }
70            }
71            _ => {
72                warn!("Unknown thing type: {}", thing.tb);
73            }
74        }
75    }
76
77    // remove duplicates
78    songs.dedup_by_key(|song| song.id.clone());
79
80    Ok(songs)
81}