src/app/config/commands.rs

6f8b64c4fa1b89868a2dbaa1bbd9fda20ecd0768
youtube-tui/src/app/config/commands.rs history · blame · raw

236 lines · 7687 bytes

  1use std::{
  2    error::Error,
  3    fs::{self, OpenOptions},
  4    io::Write,
  5};
  6
  7use serde::{Deserialize, Serialize};
  8
  9use crate::functions::insert_vec;
 10
 11use super::{Config, EnvVar};
 12
 13#[derive(Debug, Clone, Deserialize, Serialize)]
 14pub struct CommandsConfigTransitional {
 15    video_player: Option<CommandConfig>,
 16    audio_player: Option<CommandConfig>,
 17    image_viewer: Option<CommandConfig>,
 18    video_downloader: Option<CommandConfig>,
 19    audio_downloader: Option<CommandConfig>,
 20    terminal: Option<CommandConfig>,
 21    playlist_audio_all: Option<CommandConfig>,
 22    playlist_video_all: Option<CommandConfig>,
 23    playlist_shuffle_audio_all: Option<CommandConfig>,
 24    download_all_audio: Option<CommandConfig>,
 25    download_all_video: Option<CommandConfig>,
 26}
 27
 28#[derive(Clone, Debug, Serialize, Deserialize)]
 29pub struct CommandsConfig {
 30    pub video_player: CommandConfig,
 31    pub audio_player: CommandConfig,
 32    pub image_viewer: CommandConfig,
 33    pub video_downloader: CommandConfig,
 34    pub audio_downloader: CommandConfig,
 35    pub terminal: CommandConfig,
 36    pub playlist_audio_all: CommandConfig,
 37    pub playlist_video_all: CommandConfig,
 38    pub playlist_shuffle_audio_all: CommandConfig,
 39    pub download_all_audio: CommandConfig,
 40    pub download_all_video: CommandConfig,
 41}
 42
 43#[derive(Clone, Debug, Serialize, Deserialize)]
 44pub struct CommandConfig {
 45    pub command: String,
 46    pub open_in_console: bool,
 47    pub args: Vec<String>,
 48}
 49
 50impl CommandConfig {
 51    pub fn as_vec(&self) -> Vec<String> {
 52        let mut args = self.args.clone();
 53        args.insert(0, self.command.clone());
 54        args
 55    }
 56
 57    pub fn as_command_vec(self, env: EnvVar, config: &Config) -> Result<Vec<String>, ()> {
 58        let mut out;
 59        if self.open_in_console {
 60            out = config.commands.terminal.as_vec();
 61            let index = match out.iter().position(|x| x == "{command}") {
 62                Some(index) => {
 63                    out.swap_remove(index);
 64                    index
 65                }
 66                None => out.len(),
 67            };
 68
 69            insert_vec(&mut out, self.as_vec(), index);
 70        } else {
 71            out = self.as_vec();
 72        }
 73
 74        for x in out.iter_mut() {
 75            match x.as_str() {
 76                "{url}" => {
 77                    if let Some(url) = &env.url {
 78                        *x = url.clone();
 79                    } else {
 80                        return Err(());
 81                    }
 82                }
 83
 84                "{video_save_location}" => {
 85                    *x = config.main.yt_dl.video_path.clone();
 86                }
 87
 88                "{audio_save_location}" => {
 89                    *x = config.main.yt_dl.audio_path.clone();
 90                }
 91
 92                _ => {}
 93            }
 94        }
 95
 96        Ok(out)
 97    }
 98}
 99
100impl Default for CommandsConfig {
101    fn default() -> Self {
102        Self {
103            video_player: CommandConfig {
104                command: String::from("mpv"),
105                open_in_console: false,
106                args: vec![String::from("--no-terminal"), String::from("{url}")],
107            },
108            audio_player: CommandConfig {
109                command: String::from("mpv"),
110                open_in_console: true,
111                args: vec![String::from("--no-video"), String::from("{url}")],
112            },
113            image_viewer: CommandConfig {
114                command: String::from("mpv"),
115                open_in_console: false,
116                args: vec![String::from("{url}"), String::from("--no-terminal")],
117            },
118            video_downloader: CommandConfig {
119                command: String::from("yt-dlp"),
120                open_in_console: true,
121                args: vec![
122                    String::from("{url}"),
123                    String::from("-o"),
124                    String::from("{video_save_location}"),
125                ],
126            },
127            audio_downloader: CommandConfig {
128                command: String::from("yt-dlp"),
129                open_in_console: true,
130                args: vec![
131                    String::from("{url}"),
132                    String::from("-o"),
133                    String::from("{audio_save_location}"),
134                    String::from("-x"),
135                ],
136            },
137            terminal: CommandConfig {
138                command: String::from("konsole"),
139                open_in_console: false,
140                args: vec![String::from("-e"), String::from("{command}")],
141            },
142            playlist_audio_all: CommandConfig {
143                command: String::from("mpv"),
144                open_in_console: true,
145                args: vec![String::from("--no-video"), String::from("{url}")],
146            },
147            playlist_video_all: CommandConfig {
148                command: String::from("mpv"),
149                open_in_console: false,
150                args: vec![String::from("{url}"), String::from("--no-terminal")],
151            },
152            playlist_shuffle_audio_all: CommandConfig {
153                command: String::from("mpv"),
154                open_in_console: true,
155                args: vec![String::from("--no-video"), String::from("{url}"), String::from("--shuffle")],
156            },
157            download_all_audio: CommandConfig {
158                command: String::from("yt-dlp"),
159                open_in_console: true,
160                args: vec![
161                    String::from("{url}"),
162                    String::from("-o"),
163                    String::from("{audio_save_location}"),
164                    String::from("-x"),
165                ],
166            },
167            download_all_video: CommandConfig {
168                command: String::from("yt-dlp"),
169                open_in_console: true,
170                args: vec![
171                    String::from("{url}"),
172                    String::from("-o"),
173                    String::from("{video_save_location}"),
174                ],
175            },
176        }
177    }
178}
179
180impl From<CommandsConfigTransitional> for CommandsConfig {
181    fn from(original: CommandsConfigTransitional) -> CommandsConfig {
182        let mut out = Self::default();
183
184        if let Some(video_player) = original.video_player {
185            out.video_player = video_player;
186        }
187
188        if let Some(audio_player) = original.audio_player {
189            out.audio_player = audio_player;
190        }
191
192        if let Some(image_viewer) = original.image_viewer {
193            out.image_viewer = image_viewer;
194        }
195
196        if let Some(video_downloader) = original.video_downloader {
197            out.video_downloader = video_downloader;
198        }
199
200        if let Some(audio_downloader) = original.audio_downloader {
201            out.audio_downloader = audio_downloader;
202        }
203
204        if let Some(terminal) = original.terminal {
205            out.terminal = terminal;
206        }
207
208        out
209    }
210}
211
212impl CommandsConfig {
213    pub fn load() -> Result<Self, Box<dyn Error>> {
214        let mut config = home::home_dir().expect("Cannot get your home directory");
215        let mut commands = CommandsConfig::default();
216        config.push(".config");
217        config.push("youtube-tui");
218        config.push("commands.yml");
219
220        if config.exists() {
221            let content = fs::read_to_string(config.as_os_str())?;
222            let commands_transitional: CommandsConfigTransitional = serde_yaml::from_str(&content)?;
223            commands = commands_transitional.into();
224        }
225
226        let mut file = OpenOptions::new()
227            .write(true)
228            .truncate(true)
229            .create(true)
230            .open(config.as_os_str())?;
231
232        write!(file, "{}", serde_yaml::to_string(&commands)?)?;
233
234        Ok(commands)
235    }
236}