src/app/config/commands.rs

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

167 lines · 4248 bytes

  1use serde::{Deserialize, Serialize};
  2use std::{collections::HashMap, thread};
  3
  4use crate::traits::ConfigItem;
  5
  6#[derive(Serialize, Deserialize, Clone, Debug)]
  7pub struct Command {
  8    pub args: Vec<String>,
  9    pub message: String,
 10}
 11
 12#[derive(Serialize, Deserialize, Clone, Debug)]
 13pub struct CommandsConfig(pub HashMap<String, Command>);
 14
 15impl Command {
 16    pub fn as_vec(&self, variables: &HashMap<String, String>) -> Result<Vec<String>, String> {
 17        let mut out = Vec::new();
 18
 19        for arg in self.args.iter() {
 20            out.push(match check_arg(arg) {
 21                ArgType::Normal(s) => s,
 22                ArgType::Variable(s) => match variables.get(s) {
 23                    Some(s) => s.to_string(),
 24                    None => return Err(s.to_string()),
 25                },
 26            })
 27        }
 28
 29        Ok(out)
 30    }
 31
 32    pub fn run_command(&self, variables: &HashMap<String, String>) -> Option<String> {
 33        let mut args = match self.as_vec(variables) {
 34            Ok(args) => args,
 35            Err(s) => return Some(s),
 36        }
 37        .into_iter();
 38        thread::spawn(move || {
 39            let mut command = std::process::Command::new(args.next().unwrap());
 40            for arg in args {
 41                command.arg(arg);
 42            }
 43
 44            let _ = command.output();
 45        });
 46
 47        None
 48    }
 49}
 50
 51impl Default for CommandsConfig {
 52    fn default() -> Self {
 53        let mut out = Self::blank();
 54
 55        out.insert(
 56            "video_player",
 57            vec!["mpv", "{embed_url}", "--no-terminal"],
 58            "Launched mpv",
 59        );
 60        out.insert(
 61            "audio_player",
 62            vec!["konsole", "-e", "mpv", "{embed_url}", "--no-video"],
 63            "Opened mpv in new konsole window",
 64        );
 65        out.insert(
 66            "audio_playlist_shuffle",
 67            vec![
 68                "konsole",
 69                "-e",
 70                "mpv",
 71                "{embed_url}",
 72                "--no-video",
 73                "--shuffle",
 74            ],
 75            "Opened mpv in new konsole window",
 76        );
 77        out.insert(
 78            "audio_playlist_loop",
 79            vec![
 80                "konsole",
 81                "-e",
 82                "mpv",
 83                "{embed_url}",
 84                "--no-video",
 85                "--loop-playlist=inf",
 86            ],
 87            "Opened mpv in new konsole window",
 88        );
 89        out.insert(
 90            "audio_playlist_shuffle_loop",
 91            vec![
 92                "konsole",
 93                "-e",
 94                "mpv",
 95                "{embed_url}",
 96                "--no-video",
 97                "--loop-playlist=inf",
 98                "--shuffle",
 99            ],
100            "Opened mpv in new konsole window",
101        );
102        out.insert(
103            "video_downloader",
104            vec![
105                "konsole",
106                "-e",
107                "yt-dlp",
108                "{embed_url}",
109                "-o",
110                "{download_location}",
111            ],
112            "Download has started",
113        );
114
115        out.insert(
116            "audio_downloader",
117            vec![
118                "konsole",
119                "-e",
120                "yt-dlp",
121                "{embed_url}",
122                "-o",
123                "{download_location}",
124                "-x",
125            ],
126            "Download has started",
127        );
128
129        out
130    }
131}
132
133impl CommandsConfig {
134    fn blank() -> Self {
135        Self(HashMap::default())
136    }
137
138    fn insert(&mut self, label: &str, command: Vec<&str>, msg: &str) {
139        self.0.insert(
140            label.to_string(),
141            Command {
142                args: command
143                    .into_iter()
144                    .map(|item| item.to_string())
145                    .collect::<Vec<_>>(),
146                message: msg.to_string(),
147            },
148        );
149    }
150}
151
152impl ConfigItem<'_> for CommandsConfig {
153    type Struct = CommandsConfig;
154    const FILE_NAME: &'static str = "commands.yml";
155}
156enum ArgType<'a> {
157    Normal(String),
158    Variable(&'a str),
159}
160
161fn check_arg(s: &str) -> ArgType {
162    if s.starts_with('{') && s.ends_with('}') {
163        ArgType::Variable(&s[1..s.len() - 1])
164    } else {
165        ArgType::Normal(s.to_string())
166    }
167}