Skip to main content

soundcloud_rs/client/
playlists.rs

1use crate::models::client::Client;
2use crate::models::client::Identifier;
3use crate::models::error::Error;
4use crate::models::query::{Paging, PlaylistsQuery};
5use crate::models::response::{Playlist, Playlists, Users};
6use std::path::PathBuf;
7
8impl Client {
9    pub async fn search_playlists(
10        &self,
11        query: Option<&PlaylistsQuery>,
12    ) -> Result<Playlists, Error> {
13        let resp: Playlists = self.get("search/playlists", query).await?;
14        Ok(resp)
15    }
16
17    pub async fn get_playlist(
18        &self,
19        identifier: &Identifier,
20    ) -> Result<Playlist, Error> {
21        let url = format!("playlists/{identifier}");
22        let resp: Playlist = self.get(&url, None::<&()>).await?;
23        Ok(resp)
24    }
25
26    pub async fn get_playlist_reposters(
27        &self,
28        identifier: &Identifier,
29        pagination: Option<&Paging>,
30    ) -> Result<Users, Error> {
31        let url = format!("playlists/{identifier}/reposters");
32        let resp: Users = self.get(&url, pagination).await?;
33        Ok(resp)
34    }
35
36    pub async fn download_playlist(
37        &self,
38        identifier: &Identifier,
39        destination: Option<&str>,
40        playlist_name: Option<&str>,
41    ) -> Result<(), Error> {
42        let playlist = self.get_playlist(identifier).await?;
43
44        let playlist_title = match playlist_name {
45            Some(playlist_name) => playlist_name,
46            None => playlist.title.as_ref().expect("Missing playlist title"),
47        };
48
49        let output_path = match destination {
50            Some(destination) => PathBuf::from(destination).join(playlist_title),
51            None => PathBuf::from(playlist_title),
52        };
53        if !output_path.exists() {
54            std::fs::create_dir_all(&output_path)?;
55        }
56
57        let output_path_str = output_path
58            .to_str()
59            .expect("Failed to convert output path to string");
60        let tracks = playlist.tracks.as_ref().expect("Missing tracks");
61        for track in tracks {
62            let identifier = track.id.as_ref().expect("Missing track id");
63            if let Err(e) = self
64                .download_track(
65                    &Identifier::Id(*identifier),
66                    None,
67                    Some(output_path_str),
68                    None,
69                )
70                .await
71            {
72                println!("Error downloading track: {e}")
73            }
74        }
75
76        Ok(())
77    }
78}