src/app/config/main.rs
81 lines · 2118 bytes
1use std::{error::Error, fs::{self, OpenOptions}, io::Write};
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Clone, Debug, Serialize, Deserialize)]
6pub struct MainConfigTransitional {
7 pub yt_dl: Option<YtDlConfig>,
8 pub max_watch_history: Option<usize>,
9}
10
11#[derive(Clone, Debug, Serialize, Deserialize)]
12pub struct MainConfig {
13 pub yt_dl: YtDlConfig,
14 pub max_watch_history: usize,
15}
16
17impl Default for MainConfig {
18 fn default() -> Self {
19 Self {
20 yt_dl: YtDlConfig::default(),
21 max_watch_history: 50,
22 }
23 }
24}
25
26#[derive(Clone, Debug, Serialize, Deserialize)]
27pub struct YtDlConfig {
28 pub video_path: String,
29 pub audio_path: String,
30}
31
32impl Default for YtDlConfig {
33 fn default() -> Self {
34 Self {
35 video_path: String::from("~/Downloads/%(title)s.%(ext)s"),
36 audio_path: String::from("~/Downloads/%(title)s.%(ext)s"),
37 }
38 }
39}
40
41impl From<MainConfigTransitional> for MainConfig {
42 fn from(config: MainConfigTransitional) -> Self {
43 let mut out = MainConfig::default();
44
45 if let Some(yt_dl) = config.yt_dl {
46 out.yt_dl = yt_dl;
47 }
48
49 if let Some(max_watch_history) = config.max_watch_history {
50 out.max_watch_history = max_watch_history;
51 }
52
53 out
54 }
55}
56
57impl MainConfig {
58 pub fn load() -> Result<Self, Box<dyn Error>> {
59 let mut config = home::home_dir().expect("Cannot get your home directory");
60 let mut main = MainConfig::default();
61 config.push(".config");
62 config.push("youtube-tui");
63 config.push("main.yml");
64
65 if config.exists() {
66 let content = fs::read_to_string(config.as_os_str())?;
67 let main_transitional: MainConfigTransitional = serde_yaml::from_str(&content)?;
68 main = main_transitional.into();
69 }
70
71 let mut file = OpenOptions::new()
72 .write(true)
73 .truncate(true)
74 .create(true)
75 .open(config.as_os_str())?;
76
77 write!(file, "{}", serde_yaml::to_string(&main)?)?;
78
79 Ok(main)
80 }
81}