1use std::fs::File;
2use std::io::{BufReader, BufWriter};
3use std::path::{Path, PathBuf};
4use std::{fs, io};
5
6use anyhow::Result;
7
8static CRATE_NAME: &str = env!("CARGO_CRATE_NAME");
9
10pub fn initialize_config() -> Result<()> {
11 println!("Config file does not exist. Creating one now...");
12
13 let api_key = set_api_key();
14 let username = set_username();
15
16 let config = Config::new(api_key, username);
17
18 Ok(config.save_config()?)
19}
20
21fn set_api_key() -> String {
22 println!("Enter your Last.fm API key: ");
23 let mut api_key = String::new();
24 io::stdin()
25 .read_line(&mut api_key)
26 .expect("Failed to read api key");
27
28 api_key.trim().to_string()
29}
30
31fn set_username() -> String {
32 println!("Enter your Last.fm username:");
33 println!(
34 "(You can retrieve the listening history for a different Last.fm user with the `-u` flag.)"
35 );
36 let mut username = String::new();
37 io::stdin()
38 .read_line(&mut username)
39 .expect("Failed to read username");
40
41 username.trim().to_string()
42}
43
44pub fn check_if_config_exists() -> bool {
45 Path::exists(build_config_path().as_path())
46}
47
48#[derive(serde::Serialize, serde::Deserialize)]
49pub struct Config {
50 pub api_key: String,
51 pub default_username: String,
52}
53
54impl Config {
55 pub fn new(api_key: String, default_username: String) -> Self {
56 Self {
57 api_key,
58 default_username,
59 }
60 }
61
62 pub fn load_config() -> Result<Self> {
63 let file = File::open(build_config_path())?;
64 let reader = BufReader::new(file);
65 let config = match serde_json::from_reader(reader) {
68 Ok(config) => config,
69 Err(_) => {
70 eprintln!("An error occurred with your config file. Please create a new one.");
71 initialize_config()?;
72 Config::load_config()?
73 }
74 };
75
76 Ok(config)
77 }
78
79 pub fn save_config(&self) -> Result<()> {
80 let file = File::create(build_config_path())?;
81 let writer = BufWriter::new(file);
82 serde_json::to_writer(writer, &self)?;
83
84 Ok(())
85 }
86}
87
88fn build_config_path() -> PathBuf {
89 let config_dir = dirs::config_dir().unwrap();
90
91 let path = Path::new(config_dir.as_path());
92 let path = path.join(CRATE_NAME);
93
94 fs::create_dir_all(&path).expect("Path could not be created");
95
96 path.join("config.json")
97}