src/global/functions/run_command.rs

363 lines · 14859 bytes

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