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
mod auth;
mod config;
mod constant;
mod token;
mod utils;
mod client;
mod state;


pub mod require {
    pub use crate::config::{Configs, get_config, set_config};
    pub use crate::{generate_client, setup};
    pub use crate::client::Client;
    pub use rspotify::clients::BaseClient as _;
}

pub mod prelude {
    pub use super::require::*;
    pub use rspotify::prelude::*;
    pub use rspotify::model::*;
}

use std::path::Path;


pub async fn generate_client(configs: &require::Configs) -> anyhow::Result<client::Client> {
    use rspotify::clients::BaseClient;

    let auth_config = auth::AuthConfig::new(configs)?;
    let session = auth::new_session(&auth_config, true).await?;
    let state = std::sync::Arc::new(crate::state::State::new(true));

    let client = client::Client::new(session, auth_config, configs.app_config.client_id.clone(), state);
    client.refresh_token().await?;

    Ok(client)
}

pub async fn setup() -> anyhow::Result<client::Client> {
    use constant::*;
    use prelude::*;
    
    // Creating Config folders
    {
        let config_path = format!("./{}", DEFAULT_CONFIG_FOLDER);
        let config_path = Path::new(&config_path);
        let cache_path = format!("./{}", DEFAULT_CACHE_FOLDER);
        let cache_path = Path::new(&cache_path);
        
        if !config_path.exists() {
            std::fs::create_dir_all(&config_path)?;
        }
        if !cache_path.exists() {
            std::fs::create_dir_all(&cache_path)?;
        }

        let configs = Configs::from_env()?;
        set_config(configs);
    }

    let configs = get_config();
    generate_client(configs).await
}

#[cfg(test)]
mod tests {
    use super::prelude::*;
    
    #[tokio::test]
    async fn it_works() -> anyhow::Result<()> {
        let client = setup().await?;

        let playlist_id = PlaylistId::from_id("0jv39Ejx1S2MZVwS3QFC3W")?;
        let track_id = TrackId::from_id("2lKQZtNWLQyY9BiHOHUG22")?;

        client.add_track_to_playlist(playlist_id.clone(), track_id.clone()).await?;
        
        let before = client.playlist(playlist_id.clone(), None, None).await?;
        println!("{} : {} tracks", &before.name, &before.tracks.total);
        
        client.delete_track_from_playlist(playlist_id.clone(), track_id.clone()).await?;
        
        let after = client.playlist(playlist_id.clone(), None, None).await?;
        println!("{} : {} tracks", &after.name, &after.tracks.total);

        Ok(())
    }
}