src/global/functions/run_command.rs

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