src/global/functions/run_command.rs

437 lines · 18397 bytes

  1use crate::{
  2    config::*,
  3    global::{functions::*, structs::*, traits::*},
  4    load_configs,
  5};
  6use home::home_dir;
  7use std::{
  8    env,
  9    error::Error,
 10    fs,
 11    io::Stdout,
 12    process::{Command, Stdio},
 13};
 14use tui::{backend::CrosstermBackend, Terminal};
 15use tui_additions::framework::Framework;
 16
 17/// runs text command - command from the command line (not TUI) which response is just a string
 18pub fn text_command(command: &str) -> Option<String> {
 19    match command
 20        .split_ascii_whitespace()
 21        .collect::<Vec<_>>()
 22        .as_slice()
 23    {
 24        ["help"] => Some(String::from(HELP_MSG)),
 25        ["version"] => Some(format!(
 26            "{} {}",
 27            env!("CARGO_PKG_NAME"),
 28            env!("CARGO_PKG_VERSION")
 29        )),
 30        _ => None,
 31    }
 32}
 33
 34pub fn run_command(
 35    command: &str,
 36    framework: &mut Framework,
 37    terminal: &mut Terminal<CrosstermBackend<Stdout>>,
 38) {
 39    command.split(";;").into_iter().for_each(|single_command| {
 40        run_single_command(
 41            &single_command
 42                .trim()
 43                .split_ascii_whitespace()
 44                .collect::<Vec<_>>(),
 45            framework,
 46            terminal,
 47        )
 48    });
 49}
 50
 51/// runs a command in the TUI, returns true if its a loadpage command, false if not
 52pub fn run_single_command(
 53    command: &[&str],
 54    framework: &mut Framework,
 55    terminal: &mut Terminal<CrosstermBackend<Stdout>>,
 56) {
 57    // match a command splitted by space to a bunch of avaliable commands
 58    match command {
 59        [] => {}
 60        ["bookmark", id] => {
 61            match (|| -> Result<Item, Box<dyn Error>> {
 62                Ok(serde_json::from_str(&fs::read_to_string(
 63                    home_dir()
 64                        .unwrap()
 65                        .join(format!(".cache/youtube-tui/info/{id}.json")),
 66                )?)?)
 67            })() {
 68                Ok(item) => {
 69                    let library = framework.data.global.get_mut::<Library>().unwrap();
 70                    let _ = library.push(item, None);
 71                    let _ = library.save();
 72                    *framework.data.global.get_mut::<Message>().unwrap() =
 73                        Message::Success(String::from("Bookmark added"))
 74                }
 75                Err(e) => {
 76                    *framework.data.global.get_mut::<Message>().unwrap() =
 77                        Message::Error(format!("Unknown item: {e}"))
 78                }
 79            }
 80        }
 81        ["unmark", id] => {
 82            let library = framework.data.global.get_mut::<Library>().unwrap();
 83
 84            if library.remove(id) {
 85                let _ = library.save();
 86                *framework.data.global.get_mut::<Message>().unwrap() =
 87                    Message::Success(String::from("Bookmark removed"))
 88            } else {
 89                *framework.data.global.get_mut::<Message>().unwrap() =
 90                    Message::Error(String::from("No item with that ID found"))
 91            }
 92        }
 93        ["togglemark", id] => {
 94            let library = framework.data.global.get_mut::<Library>().unwrap();
 95            if library.remove(id) {
 96                let _ = library.save();
 97                *framework.data.global.get_mut::<Message>().unwrap() =
 98                    Message::Success(String::from("Bookmark removed"))
 99            } else {
100                run_single_command(&["bookmark", id], framework, terminal);
101            }
102        }
103        ["help"] | ["h"] => {
104            *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(String::from(
105                "Avaliable commands can be viewed by running `youtube-tui help` in terminal",
106            ));
107        }
108        ["switchprovider"] => {
109            let status = framework.data.global.get_mut::<Status>().unwrap();
110
111            status.provider.rotate();
112            status.provider_updated = true;
113            *framework.data.global.get_mut::<Message>().unwrap() =
114                Message::Success(format!("Provider updated to {}", status.provider.as_str()));
115            update_provider(&mut framework.data);
116        }
117        ["loadpage"] => {
118            *framework.data.global.get_mut::<Message>().unwrap() =
119                Message::Message(String::from("Usage: `loadpage {page}`"));
120        }
121        // loads a given page
122        ["loadpage", page, ..] => {
123            let page = match *page {
124                "popular" => Some(Page::MainMenu(MainMenuPage::Popular)),
125                "trending" => Some(Page::MainMenu(MainMenuPage::Trending)),
126                "watchhistory" => Some(Page::MainMenu(MainMenuPage::History)),
127                "subscriptions" => Some(Page::MainMenu(MainMenuPage::Subscriptions)),
128                "library" => Some(Page::MainMenu(MainMenuPage::Library)),
129                "channel" => {
130                    if command.len() == 2 {
131                        *framework.data.global.get_mut::<Message>().unwrap() =
132                            Message::Message(String::from("Usage: `loadpage channel {id/url}`"));
133                        return;
134                    }
135
136                    match from_channel_url(command[2]) {
137                        Ok(id) => Some(Page::ChannelDisplay(ChannelDisplayPage {
138                            id,
139                            r#type: ChannelDisplayPageType::Main,
140                        })),
141                        Err(e) => {
142                            *framework.data.global.get_mut::<Message>().unwrap() =
143                                Message::Error(e);
144                            return;
145                        }
146                    }
147                }
148                "video" => {
149                    if command.len() == 2 {
150                        *framework.data.global.get_mut::<Message>().unwrap() =
151                            Message::Message(String::from("Usage: `loadpage video {id/url}`"));
152                        return;
153                    }
154
155                    match from_video_url(command[2]) {
156                        Ok(id) => Some(Page::SingleItem(SingleItemPage::Video(id))),
157                        Err(e) => {
158                            *framework.data.global.get_mut::<Message>().unwrap() =
159                                Message::Error(e);
160                            return;
161                        }
162                    }
163                }
164                "playlist" => {
165                    if command.len() == 2 {
166                        *framework.data.global.get_mut::<Message>().unwrap() =
167                            Message::Message(String::from("Usage: `loadpage playlist {id/url}`"));
168                        return;
169                    }
170
171                    match from_playlist_url(command[2]) {
172                        Ok(id) => Some(Page::SingleItem(SingleItemPage::Playlist(id))),
173                        Err(e) => {
174                            *framework.data.global.get_mut::<Message>().unwrap() =
175                                Message::Error(e);
176                            return;
177                        }
178                    }
179                }
180                "search" => {
181                    if command.len() == 2 {
182                        *framework.data.global.get_mut::<Message>().unwrap() =
183                            Message::Message(String::from("Usage: `search {query}`"));
184                        return;
185                    }
186
187                    // search for a query, although the command is matched as an array, the original query can
188                    // be reconstructed by joining the string with a space in between
189                    let search = framework.data.state.get_mut::<Search>().unwrap();
190                    search.query = command[2..].join(" ");
191                    let cloned = search.clone();
192                    Some(Page::Search(cloned))
193                }
194                _ => {
195                    *framework.data.global.get_mut::<Message>().unwrap() =
196                        Message::Error(format!("Unknown page: `{page}`"));
197                    None
198                }
199            };
200
201            if let Some(page) = page {
202                framework
203                    .data
204                    .state
205                    .get_mut::<Tasks>()
206                    .unwrap()
207                    .priority
208                    .push(Task::LoadPage(page))
209            }
210        }
211        // redirects to the relevant `loadpage` command
212        ["popular"] => run_single_command(&["loadpage", "popular"], framework, terminal),
213        ["trending"] => run_single_command(&["loadpage", "trending"], framework, terminal),
214        ["watchhistory"] => run_single_command(&["loadpage", "watchhistory"], framework, terminal),
215        ["subscriptions"] => {
216            run_single_command(&["loadpage", "subscriptions"], framework, terminal)
217        }
218        ["bookmarks"] => run_single_command(&["loadpage", "bookmarks"], framework, terminal),
219        ["library"] => run_single_command(&["loadpage", "library"], framework, terminal),
220        ["search"] => run_single_command(&["loadpage", "search"], framework, terminal),
221        ["search", ..] => run_single_command(
222            &format!("loadpage search {}", command[1..].join(" "))
223                .split(' ')
224                .collect::<Vec<&str>>(),
225            framework,
226            terminal,
227        ),
228        ["channel"] => run_single_command(&["loadpage", "channel"], framework, terminal),
229        ["channel", identifier] => {
230            run_single_command(&["loadpage", "channel", *identifier], framework, terminal)
231        }
232        ["video"] => run_single_command(&["loadpage", "video"], framework, terminal),
233        ["video", identifier] => {
234            run_single_command(&["loadpage", "video", *identifier], framework, terminal)
235        }
236        ["playlist"] => run_single_command(&["loadpage", "playlist"], framework, terminal),
237        ["playlist", identifier] => {
238            run_single_command(&["loadpage", "playlist", *identifier], framework, terminal)
239        }
240        ["history"] => {
241            *framework.data.global.get_mut::<Message>().unwrap() =
242                Message::Message(String::from("Usage: `history [back/clear]`"))
243        }
244        ["history", "back"] | ["back"] => {
245            let _ = framework.revert_last_history();
246            framework
247                .data
248                .state
249                .get_mut::<Tasks>()
250                .unwrap()
251                .priority
252                .push(Task::ClearPage);
253            framework
254                .data
255                .state
256                .get_mut::<Tasks>()
257                .unwrap()
258                .priority
259                .push(Task::RenderAll);
260            run_single_command(&["flush"], framework, terminal);
261            framework
262                .data
263                .global
264                .get_mut::<Status>()
265                .unwrap()
266                .render_image = true;
267        }
268        ["history", "clear"] => {
269            framework.clear_history();
270        }
271        ["flush"] => loop {
272            // runs all stacked actions
273            if let Some(tasks) = framework.data.state.get_mut::<Tasks>().unwrap().pop() {
274                let _res = tasks.run(framework, terminal);
275                continue;
276            }
277            break;
278        },
279        ["reload"] | ["r"] => {
280            framework
281                .data
282                .state
283                .get_mut::<Tasks>()
284                .unwrap()
285                .priority
286                .push(Task::Reload);
287        }
288        ["reload", "config"] | ["reload", "configs"] | ["r", "config"] | ["r", "configs"] => {
289            *framework.data.global.get_mut::<Message>().unwrap() =
290                match load_configs(&mut framework.split_clean().0) {
291                    Ok(()) => Message::Success(String::from("Config files have been reloaded")),
292                    Err(e) => Message::Error(e.to_string()),
293                };
294        }
295        ["q"] | ["quit"] | ["x"] | ["exit"] => {
296            framework.data.global.get_mut::<Status>().unwrap().exit = true;
297        }
298        ["hello", "world"] => {
299            let index = fake_rand_range(0, HELLO_WORLDS.len() as i64) as usize;
300            *framework.data.global.get_mut::<Message>().unwrap() =
301                Message::Message(format!("Line #{index}: {}", HELLO_WORLDS[index]));
302        }
303        ["version"] | ["v"] => {
304            *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(format!(
305                "{} {}",
306                env!("CARGO_PKG_NAME"),
307                env!("CARGO_PKG_VERSION")
308            ));
309        }
310        ["run"] | ["parrun"] => {
311            *framework.data.global.get_mut::<Message>().unwrap() =
312                Message::Message(String::from("Usage: run/parrun [command]"));
313        }
314        ["run", ..] => {
315            let command = command[1..].join(" ");
316            *framework.data.global.get_mut::<Message>().unwrap() =
317                Message::Success(command.clone());
318            if let Ok(mut child) =
319                Command::new(&framework.data.global.get::<MainConfig>().unwrap().shell)
320                    .args(["-c", &command])
321                    .stdout(Stdio::null())
322                    .stderr(Stdio::null())
323                    .spawn()
324            {
325                let _ = child.wait();
326            }
327        }
328        ["parrun", ..] => {
329            let command = command[1..].join(" ");
330            *framework.data.global.get_mut::<Message>().unwrap() =
331                Message::Success(command.clone());
332            let _ = Command::new(&framework.data.global.get::<MainConfig>().unwrap().shell)
333                .args(["-c", &command])
334                .stdout(Stdio::null())
335                .stderr(Stdio::null())
336                .spawn();
337        }
338        ["copy"] | ["cp"] => {
339            *framework.data.global.get_mut::<Message>().unwrap() =
340                Message::Message(String::from("Usage: copy [text]"));
341        }
342        #[cfg(feature = "clipboard")]
343        ["copy", ..] | ["cp", ..] => {
344            set_clipboard(command[1..].join(" "));
345            *framework.data.global.get_mut::<Message>().unwrap() =
346                Message::Success(String::from("Copied to clipboad"));
347        }
348        _ => {
349            *framework.data.global.get_mut::<Message>().unwrap() =
350                Message::Error(format!("Unknown command: `{}`", command.join(" ")));
351        }
352    }
353}
354
355const HELLO_WORLDS: &[&str] = &[
356    "printf(\"Hello World\")",
357    "std::cout << \"Hello World\"",
358    "DISPLAY \"Hello World\".    .",
359    "printIn(\"Hello World\")",
360    "disp('Hello World')",
361    "System.Console.WriteLine(\"Hello World\")",
362    "console.lof 'Hello World'",
363    "WriteLn('Hello World')",
364    "print('Hello World')",
365    "main = putStrLn \"Hello World\"",
366    "writeln ('Hello, world.')",
367    "puts 'Hello World'",
368    "print(\"Hello World\")",
369    "db    'Hello World', 10, 0",
370    "cat('Hello World')",
371    "println('Hello World')",
372    "echo \"Hello World\"",
373    "System.out.println(\"Hello World\")",
374    "println('Hello World\")",
375    "printfn \"Hello World\"",
376    "(print \"Hello World\")",
377    "console.log(\"Hello World\")",
378    "BEGIN DISPLAY(\"Hello World\") END.",
379    "print \"Hello World\"",
380    "puts \"Hello World\"",
381    "console.log 'Hello World'",
382    "print *, \"Hello World\"",
383    "<h1>Hello World<\\h1>",
384];
385
386const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
387
388\x1b[37mfor more visit https://siriusmart.github.io/youtube-tui/commands.html\x1b[0m
389
390\x1b[91mUSAGE:\x1b[0m
391    youtube-tui (command)
392
393\x1b[91mINFORMATIONAL:\x1b[0m
394    \x1b[33mhelp\x1b[0m                            Display this message
395    \x1b[33mversion\x1b[0m                         Print version info and exit
396
397\x1b[91mLOADPAGE:
398\x1b[37mloadpage [page] loads the corresponding page\x1b[0m
399    \x1b[33mloadpage popular\x1b[0m                Loads the popular videos page
400    \x1b[33mloadpage trending\x1b[0m               Loads the trending videos page
401    \x1b[33mloadpage watchhistory\x1b[0m           Loads the watch history page
402    \x1b[33mloadpage subscriptions\x1b[0m          Loads the subscriptions page
403    \x1b[33mloadpage bookmarks\x1b[0m              Loads the bookmarks page
404    \x1b[33mloadpage library\x1b[0m                Loads the library (saved items) page
405    \x1b[33mloadpage search [query]\x1b[0m         Loads the search page with the given query
406    \x1b[33mloadpage video [identifier]\x1b[0m     Loads the video item page
407    \x1b[33mloadpage playlist [identifier]\x1b[0m  Loads the playlist item page
408    \x1b[33mloadpage channel [identifier]\x1b[0m   Loads the channel item page
409
410\x1b[91mHISTORY:\x1b[0m
411    \x1b[33mhistory back\x1b[0m                    Revert back to previous state
412    \x1b[33mhistory clear\x1b[0m                   Clear all previously saved states, making the current state the original
413
414\x1b[91mUTILITY:\x1b[0m
415    \x1b[33mreload\x1b[0m                          Reloads the current page
416    \x1b[33mreload configs\x1b[0m                  Reload all config files
417    \x1b[33mflush\x1b[0m                           Run all tasks in queue immediately
418    \x1b[33mquit\x1b[0m                            Immediately exit
419    \x1b[33mrun [command]\x1b[0m                   Runs a system command (e.g. `run rm -rf / --no-preserve-root`)
420    \x1b[33mparrun [command]\x1b[0m                Runs a system command non blocking (e.g. `run firefox example.com`)
421    \x1b[33mcopy [text]\x1b[0m                     Copies text to clipboard
422
423\x1b[91mLIBRARY:\x1b[0m
424    \x1b[33mbookmark [id]\x1b[0m                   Bookmark item with ID (item must be already loaded)
425    \x1b[33munmark [id]\x1b[0m                     Remove bookmark item with ID
426    \x1b[33mtogglemark [id]\x1b[0m                 Toggle bookmark status
427
428\x1b[91mALT:\x1b[0m
429\x1b[37malts links back to the original command\x1b[30m
430    \x1b[33m[page] (additional options)\x1b[0m     `loadpage [page]`
431    \x1b[33mback\x1b[0m                            `history back`
432    \x1b[33mr\x1b[0m                               `reload`
433    \x1b[33mreload/r config/configs\x1b[0m         `reload configs`
434    \x1b[33mq, exit, x\x1b[0m                      `quit`
435    \x1b[33mcp [text]\x1b[0m                       `copy [text]`
436
437\x1b[37mOnly load page and informational commands can be used from command line, the rest can only be used in (`:`) command mode inside the TUI.\x1b[0m";