src/global/functions/run_command.rs

425 lines · 17862 bytes

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