src/global/functions/run_command.rs

737 lines · 31009 bytes

  1use crate::{
  2    config::{serde::KeyCodeSerde, *},
  3    global::{functions::*, structs::*, traits::*},
  4    load_configs,
  5};
  6use crossterm::event::{KeyEvent, KeyModifiers};
  7use home::home_dir;
  8use ratatui::{backend::CrosstermBackend, Terminal};
  9use std::{
 10    env,
 11    error::Error,
 12    fs,
 13    io::Stdout,
 14    process::{Command, Stdio},
 15    sync::Arc,
 16};
 17use tui_additions::framework::Framework;
 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    let command_parts: Vec<&str> = command.split_ascii_whitespace().collect();
 22
 23    match command_parts.as_slice() {
 24        ["help"] => Some(help_msg(
 25            &CommandsRemapConfig::load(WriteConfig::Dont).unwrap(),
 26        )),
 27        ["version"] => Some(format!(
 28            "{} {}",
 29            env!("CARGO_PKG_NAME"),
 30            env!("CARGO_PKG_VERSION")
 31        )),
 32        ["loadpage", page, ..] => {
 33            // Validate loadpage commands from command line to prevent hanging in raw screen
 34            match *page {
 35                "popular" | "trending" | "watchhistory" | "feed" | "library" => {
 36                    if command_parts.len() != 2 {
 37                        return Some(format!("Usage: `loadpage {}`", page));
 38                    }
 39                    None // Let it proceed to TUI
 40                }
 41                "channel" | "video" | "playlist" => {
 42                    if command_parts.len() != 3 {
 43                        return Some(format!("Usage: `loadpage {} {{id/url}}`", page));
 44                    }
 45                    None // Let it proceed to TUI
 46                }
 47                "search" => {
 48                    if command_parts.len() < 3 {
 49                        return Some("Usage: `loadpage search {query}`".to_string());
 50                    }
 51                    None // Let it proceed to TUI
 52                }
 53                _ => Some(format!("Unknown page: `{}`", page)),
 54            }
 55        }
 56        _ => {
 57            // Check if this is a remapped command that would become a loadpage command
 58            if let Some(remapped_cmd) = CommandsRemapConfig::load(WriteConfig::Dont)
 59                .unwrap()
 60                .get(&command_parts)
 61            {
 62                // If it remaps to a loadpage command, validate it
 63                if remapped_cmd.starts_with("loadpage ") {
 64                    let remapped_parts: Vec<&str> = remapped_cmd.split_ascii_whitespace().collect();
 65                    if remapped_parts.len() >= 2 {
 66                        let page = remapped_parts[1];
 67                        match page {
 68                            "popular" | "trending" | "watchhistory" | "feed" | "library" => {
 69                                if command_parts.len() != 1 {
 70                                    return Some(format!("Usage: `{}`", command_parts[0]));
 71                                }
 72                            }
 73                            "channel" | "video" | "playlist" => {
 74                                if command_parts.len() != 2 {
 75                                    return Some(format!(
 76                                        "Usage: `{} {{id/url}}`",
 77                                        command_parts[0]
 78                                    ));
 79                                }
 80                            }
 81                            "search" => {
 82                                if command_parts.len() < 2 {
 83                                    return Some(format!(
 84                                        "Usage: `{} {{query}}`",
 85                                        command_parts[0]
 86                                    ));
 87                                }
 88                            }
 89                            _ => {}
 90                        }
 91                    }
 92                }
 93            }
 94            None
 95        }
 96    }
 97}
 98
 99pub fn run_command(
100    command: &str,
101    framework: &mut Framework,
102    terminal: &mut Terminal<CrosstermBackend<Stdout>>,
103) {
104    command.split(";;").for_each(|single_command| {
105        run_single_command(
106            &single_command
107                .trim()
108                .split_ascii_whitespace()
109                .collect::<Vec<_>>(),
110            framework,
111            terminal,
112        )
113    });
114}
115
116/// runs a command in the TUI, returns true if its a loadpage command, false if not
117pub fn run_single_command(
118    command: &[&str],
119    framework: &mut Framework,
120    terminal: &mut Terminal<CrosstermBackend<Stdout>>,
121) {
122    // match a command splitted by space to a bunch of avaliable commands
123    match command {
124        [] => {}
125        ["bookmark", id] => {
126            match (|| -> Result<Item, Box<dyn Error>> {
127                Ok(serde_json::from_str(&fs::read_to_string(
128                    home_dir()
129                        .unwrap()
130                        .join(format!(".cache/youtube-tui/info/{id}.json")),
131                )?)?)
132            })() {
133                Ok(item) => {
134                    let library = framework.data.global.get_mut::<Library>().unwrap();
135                    let _ = library.push(item);
136                    let _ = library.save();
137                    *framework.data.global.get_mut::<Message>().unwrap() =
138                        Message::Success(String::from("Bookmark added"))
139                }
140                Err(e) => {
141                    *framework.data.global.get_mut::<Message>().unwrap() =
142                        Message::Error(format!("Unknown item: {e}"))
143                }
144            }
145        }
146        ["unmark", id] => {
147            let library = framework.data.global.get_mut::<Library>().unwrap();
148
149            if library.remove(id) {
150                let _ = library.save();
151                *framework.data.global.get_mut::<Message>().unwrap() =
152                    Message::Success(String::from("Bookmark removed"))
153            } else {
154                *framework.data.global.get_mut::<Message>().unwrap() =
155                    Message::Error(String::from("No item with that ID found"))
156            }
157        }
158        ["togglemark", id] => {
159            let library = framework.data.global.get_mut::<Library>().unwrap();
160            if library.remove(id) {
161                let _ = library.save();
162                *framework.data.global.get_mut::<Message>().unwrap() =
163                    Message::Success(String::from("Bookmark removed"))
164            } else {
165                run_single_command(&["bookmark", id], framework, terminal);
166            }
167        }
168        ["help"] => {
169            *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(String::from(
170                "Avaliable commands can be viewed by running `youtube-tui help` in terminal",
171            ));
172        }
173        ["switchprovider"] => {
174            let status = framework.data.global.get_mut::<Status>().unwrap();
175
176            status.provider.rotate();
177            status.provider_updated = true;
178            *framework.data.global.get_mut::<Message>().unwrap() =
179                Message::Success(format!("Provider updated to {}", status.provider.as_str()));
180            update_provider(&mut framework.data);
181        }
182        // loads a given page
183        ["loadpage", page, ..] => {
184            let page = match *page {
185                "popular" => Some(Page::MainMenu(MainMenuPage::Popular)),
186                "trending" => Some(Page::MainMenu(MainMenuPage::Trending)),
187                "watchhistory" => Some(Page::MainMenu(MainMenuPage::History)),
188                "feed" => Some(Page::Feed),
189                "library" => Some(Page::MainMenu(MainMenuPage::Library)),
190                "channel" => {
191                    if command.len() != 3 {
192                        *framework.data.global.get_mut::<Message>().unwrap() =
193                            Message::Message(String::from("Usage: `loadpage channel {id/url}`"));
194                        return;
195                    }
196
197                    match from_channel_url(command[2]) {
198                        Ok(id) => Some(Page::ChannelDisplay(ChannelDisplayPage {
199                            id,
200                            r#type: ChannelDisplayPageType::Main,
201                        })),
202                        Err(e) => {
203                            *framework.data.global.get_mut::<Message>().unwrap() =
204                                Message::Error(e);
205                            return;
206                        }
207                    }
208                }
209                "video" => {
210                    if command.len() != 3 {
211                        *framework.data.global.get_mut::<Message>().unwrap() =
212                            Message::Message(String::from("Usage: `loadpage video {id/url}`"));
213                        return;
214                    }
215
216                    match from_video_url(command[2]) {
217                        Ok(id) => Some(Page::SingleItem(SingleItemPage::Video(id))),
218                        Err(e) => {
219                            *framework.data.global.get_mut::<Message>().unwrap() =
220                                Message::Error(e);
221                            return;
222                        }
223                    }
224                }
225                "playlist" => {
226                    if command.len() != 3 {
227                        *framework.data.global.get_mut::<Message>().unwrap() =
228                            Message::Message(String::from("Usage: `loadpage playlist {id/url}`"));
229                        return;
230                    }
231
232                    match from_playlist_url(command[2]) {
233                        Ok(id) => Some(Page::SingleItem(SingleItemPage::Playlist(id))),
234                        Err(e) => {
235                            *framework.data.global.get_mut::<Message>().unwrap() =
236                                Message::Error(e);
237                            return;
238                        }
239                    }
240                }
241                "search" => {
242                    if command.len() == 2 {
243                        *framework.data.global.get_mut::<Message>().unwrap() =
244                            Message::Message(String::from("Usage: `search {query}`"));
245                        return;
246                    }
247
248                    // search for a query, although the command is matched as an array, the original query can
249                    // be reconstructed by joining the string with a space in between
250                    let search = framework.data.state.get_mut::<Search>().unwrap();
251                    search.query = command[2..].join(" ");
252                    let cloned = search.clone();
253                    Some(Page::Search(cloned))
254                }
255                _ => {
256                    *framework.data.global.get_mut::<Message>().unwrap() =
257                        Message::Error(format!("Unknown page: `{page}`"));
258                    None
259                }
260            };
261
262            if let Some(page) = page {
263                framework
264                    .data
265                    .state
266                    .get_mut::<Tasks>()
267                    .unwrap()
268                    .priority
269                    .push(Task::LoadPage(page))
270            }
271        }
272        ["history", "back"] | ["back"] => {
273            let _ = framework.revert_last_history();
274            framework
275                .data
276                .state
277                .get_mut::<Tasks>()
278                .unwrap()
279                .priority
280                .push(Task::ClearPage);
281            framework
282                .data
283                .state
284                .get_mut::<Tasks>()
285                .unwrap()
286                .priority
287                .push(Task::RenderAll);
288            run_single_command(&["flush"], framework, terminal);
289            framework
290                .data
291                .global
292                .get_mut::<Status>()
293                .unwrap()
294                .render_image = true;
295        }
296        ["history", "clear"] => {
297            framework.clear_history();
298        }
299        ["flush"] => loop {
300            // runs all stacked actions
301            if let Some(tasks) = framework.data.state.get_mut::<Tasks>().unwrap().pop() {
302                let _res = tasks.run(framework, terminal);
303                continue;
304            }
305            break;
306        },
307        ["reload"] | ["r"] => {
308            framework
309                .data
310                .state
311                .get_mut::<Tasks>()
312                .unwrap()
313                .priority
314                .push(Task::Reload);
315        }
316        ["reload", "configs"] => {
317            *framework.data.global.get_mut::<Message>().unwrap() =
318                match load_configs(&mut framework.split_clean().0) {
319                    Ok(()) => Message::Success(String::from("Config files have been reloaded")),
320                    Err(e) => Message::Error(e.to_string()),
321                };
322        }
323        ["quit"] => {
324            framework.data.global.get_mut::<Status>().unwrap().exit = true;
325        }
326        ["hello", "world"] => {
327            let index = fake_rand_range(0, HELLO_WORLDS.len() as i64) as usize;
328            *framework.data.global.get_mut::<Message>().unwrap() =
329                Message::Message(format!("Line #{index}: {}", HELLO_WORLDS[index]));
330        }
331        ["version"] => {
332            *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(format!(
333                "{} {}",
334                env!("CARGO_PKG_NAME"),
335                env!("CARGO_PKG_VERSION")
336            ));
337        }
338        ["run", ..] => {
339            let command = command[1..].join(" ");
340            *framework.data.global.get_mut::<Message>().unwrap() =
341                Message::Success(command.clone());
342            if let Ok(mut child) =
343                Command::new(&framework.data.global.get::<MainConfig>().unwrap().shell)
344                    .args(["-c", &command])
345                    .stdout(Stdio::null())
346                    .stderr(Stdio::null())
347                    .spawn()
348            {
349                let _ = child.wait();
350            }
351        }
352        ["parrun", ..] => {
353            let command = command[1..].join(" ");
354            *framework.data.global.get_mut::<Message>().unwrap() =
355                Message::Success(command.clone());
356            let _ = Command::new(&framework.data.global.get::<MainConfig>().unwrap().shell)
357                .args(["-c", &command])
358                .stdout(Stdio::null())
359                .stderr(Stdio::null())
360                .spawn();
361        }
362        #[cfg(feature = "clipboard")]
363        ["copy", ..] => {
364            set_clipboard(command[1..].join(" "));
365            *framework.data.global.get_mut::<Message>().unwrap() =
366                Message::Success(String::from("Copied to clipboad"));
367        }
368        #[cfg(not(feature = "clipboard"))]
369        ["copy", ..] => {
370            *framework.data.global.get_mut::<Message>().unwrap() = Message::Error(String::from(
371                "Feature `clipboard` is disabled and not compiled",
372            ));
373        }
374        ["sync", identifier] => {
375            let id = if identifier.len() == 24 {
376                identifier.to_string()
377            } else {
378                let splitted = identifier.split_once("/channel/");
379
380                match splitted {
381                    Some((_, actual_stuff)) if actual_stuff.len() >= 24 => {
382                        actual_stuff[0..24].to_string()
383                    }
384                    _ => {
385                        *framework.data.global.get_mut::<Message>().unwrap() =
386                            Message::Error(String::from("Invalid identifier: no channel ID found"));
387                        return;
388                    }
389                }
390            };
391
392            *framework.data.global.get_mut::<Message>().unwrap() =
393                Message::Message(String::from("Syncing..."));
394            terminal.draw(|frame| framework.render(frame)).unwrap();
395
396            let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
397            let image_index = mainconfig.image_index;
398            let download_thumbnails = mainconfig.images.display();
399            let syncing = mainconfig.syncing;
400
401            let subscriptions = framework.data.global.get_mut::<Subscriptions>().unwrap();
402
403            let message =
404                match subscriptions.sync_one(&id, image_index, download_thumbnails, &syncing) {
405                    Ok(()) => Message::Success(String::from("Channel synced")),
406                    Err(e) => Message::Error(format!("Sync failed: {e}")),
407                };
408
409            if framework.data.state.get::<Page>().unwrap() == &Page::Feed {
410                let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
411                tasks.priority.push(Task::Reload);
412                // tasks.priority.reload_render = false;
413                tasks.priority.push(Task::Custom(TaskFunction::new(Arc::new(
414                    move |framework| {
415                        *framework.data.global.get_mut::<Message>().unwrap() = message.clone();
416                    },
417                ))));
418                tasks.last.push(Task::RenderAll);
419            } else {
420                *framework.data.global.get_mut::<Message>().unwrap() = message;
421                framework
422                    .data
423                    .state
424                    .get_mut::<Tasks>()
425                    .unwrap()
426                    .priority
427                    .push(Task::RenderAll);
428            }
429        }
430        ["unsub", identifier] => {
431            let id = if identifier.len() == 24 {
432                identifier.to_string()
433            } else {
434                let splitted = identifier.split_once("/channel/");
435
436                match splitted {
437                    Some((_, actual_stuff)) if actual_stuff.len() >= 24 => {
438                        actual_stuff[0..24].to_string()
439                    }
440                    _ => {
441                        *framework.data.global.get_mut::<Message>().unwrap() =
442                            Message::Error(String::from("Invalid identifier: no channel ID found"));
443                        return;
444                    }
445                }
446            };
447
448            let message = if framework
449                .data
450                .global
451                .get_mut::<Subscriptions>()
452                .unwrap()
453                .remove_one(&id)
454            {
455                Message::Success(String::from("Unsubscribed from channel"))
456            } else {
457                Message::Error(String::from("Channel not found in subscriptions"))
458            };
459
460            if framework.data.state.get::<Page>().unwrap() == &Page::Feed {
461                let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
462                tasks.priority.push(Task::Reload);
463                // tasks.priority.reload_render = false;
464                tasks.priority.push(Task::Custom(TaskFunction::new(Arc::new(
465                    move |framework| {
466                        *framework.data.global.get_mut::<Message>().unwrap() = message.clone();
467                    },
468                ))));
469                tasks.last.push(Task::RenderAll);
470            } else {
471                *framework.data.global.get_mut::<Message>().unwrap() = message;
472                framework
473                    .data
474                    .state
475                    .get_mut::<Tasks>()
476                    .unwrap()
477                    .priority
478                    .push(Task::RenderAll);
479            }
480        }
481        ["syncall"] => {
482            *framework.data.global.get_mut::<Message>().unwrap() =
483                Message::Message(String::from("Syncing..."));
484            terminal.draw(|frame| framework.render(frame)).unwrap();
485
486            let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
487            let image_index = mainconfig.image_index;
488            let download_thumbnails = mainconfig.images.display();
489            let syncing = mainconfig.syncing;
490
491            let (success, failed, empty, cached) = framework
492                .data
493                .global
494                .get_mut::<Subscriptions>()
495                .unwrap()
496                .sync(image_index, download_thumbnails, syncing);
497
498            let message = Message::Success(format!(
499                "Subscriptions synced: {success} success{} | {failed} fail | {cached} cached",
500                if empty != 0 {
501                    format!(" (which {empty} empty)")
502                } else {
503                    String::new()
504                }
505            ));
506
507            if framework.data.state.get::<Page>().unwrap() == &Page::Feed {
508                let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
509                tasks.priority.push(Task::Reload);
510                // tasks.priority.reload_render = false;
511                tasks.priority.push(Task::Custom(TaskFunction::new(Arc::new(
512                    move |framework| {
513                        *framework.data.global.get_mut::<Message>().unwrap() = message.clone();
514                    },
515                ))));
516                tasks.last.push(Task::RenderAll);
517            } else {
518                *framework.data.global.get_mut::<Message>().unwrap() = message;
519                framework
520                    .data
521                    .state
522                    .get_mut::<Tasks>()
523                    .unwrap()
524                    .priority
525                    .push(Task::RenderAll);
526            }
527        }
528        ["key", keycode, modifier] => {
529            let (keycodeserde, modifier) =
530                match (|| -> Result<(KeyCodeSerde, u8), Box<dyn Error>> {
531                    Ok((serde_yaml_ng::from_str(keycode)?, modifier.parse()?))
532                })() {
533                    Ok(stuff) => stuff,
534                    Err(e) => {
535                        *framework.data.global.get_mut::<Message>().unwrap() =
536                            Message::Error(format!("Cannot parse keycode: `{e}`"));
537                        return;
538                    }
539                };
540            let keycode = match keycodeserde.to_keycode() {
541                Some(code) => code,
542                None => {
543                    *framework.data.global.get_mut::<Message>().unwrap() =
544                        Message::Error("Unknown keycode".to_string());
545                    return;
546                }
547            };
548            let keymodifier = KeyModifiers::from_bits_truncate(modifier);
549            key_input(KeyEvent::new(keycode, keymodifier), framework, terminal)
550        }
551        #[cfg(feature = "mpv")]
552        ["mpv", "prop", property] => {
553            let res = framework
554                .data
555                .global
556                .get::<MpvWrapper>()
557                .unwrap()
558                .property(property.to_string());
559
560            *framework.data.global.get_mut::<Message>().unwrap() = match res {
561                Some(value) => Message::Message(format!("Value: `{value}`")),
562                None => Message::Error("No such property".to_string()),
563            };
564        }
565        #[cfg(feature = "mpv")]
566        ["mpv", "tprop", property] => {
567            let mpv = framework.data.global.get::<MpvWrapper>().unwrap();
568            let res = mpv.property(property.to_string());
569
570            let toset = match res {
571                Some(value) if value.as_str() == "yes" || value.as_str() == "true" => "no",
572                _ => "yes",
573            };
574
575            let res = mpv.set_property(property.to_string(), toset.to_string());
576            *framework.data.global.get_mut::<Message>().unwrap() = match res {
577                MpvResponse::Copy => Message::Mpv(format!("Set `{property}` to `{toset}`")),
578                MpvResponse::Error(e) => Message::Error(format!("MPV error: {e}")),
579                _ => unreachable!(),
580            };
581        }
582        #[cfg(feature = "mpv")]
583        ["mpv", "sprop", name, ..] => {
584            let value = command[3..].join(" ");
585            let res = framework
586                .data
587                .global
588                .get::<MpvWrapper>()
589                .unwrap()
590                .set_property(name.to_string(), value.clone());
591
592            *framework.data.global.get_mut::<Message>().unwrap() = match res {
593                // MpvResponse::Copy => Message::Mpv(format!("Set `{name}` to `{value}`")),
594                MpvResponse::Copy => return,
595                MpvResponse::Error(e) => Message::Mpv(format!("MPV error: {e}")),
596                _ => unreachable!(),
597            };
598        }
599        #[cfg(feature = "mpv")]
600        ["mpv", name, ..] => {
601            let res = framework.data.global.get::<MpvWrapper>().unwrap().command(
602                name.to_string(),
603                command[2..].iter().map(|s| s.to_string()).collect(),
604            );
605
606            *framework.data.global.get_mut::<Message>().unwrap() = match res {
607                // MpvResponse::Copy => Message::Mpv("MPV player OK.".to_string()),
608                MpvResponse::Copy => return,
609                MpvResponse::Error(e) => Message::Mpv(format!("MPV error: {e}")),
610                _ => unreachable!(),
611            };
612        }
613        #[cfg(not(feature = "mpv"))]
614        ["mpv", ..] => {
615            *framework.data.global.get_mut::<Message>().unwrap() =
616                Message::Error(String::from("Feature `mpv` is disabled and not compiled"));
617        }
618        ["echo", r#type, ..] => {
619            *framework.data.global.get_mut::<Message>().unwrap() = match *r#type {
620                "message" => Message::Message(command[2..].join(" ")),
621                "mpv" => Message::Mpv(command[2..].join(" ")),
622                "success" => Message::Success(command[2..].join(" ")),
623                "error" => Message::Error(command[2..].join(" ")),
624                "none" => Message::None,
625                _ => Message::Error(format!("Unknown type `{}`", r#type)),
626            }
627        }
628        _ => {
629            if let Some(cmd) = framework
630                .data
631                .global
632                .get_mut::<CommandsRemapConfig>()
633                .unwrap()
634                .get(command)
635            {
636                run_command(&cmd, framework, terminal);
637                return;
638            }
639
640            *framework.data.global.get_mut::<Message>().unwrap() =
641                Message::Error(format!("Unknown command: `{}`", command.join(" ")));
642        }
643    }
644}
645
646const HELLO_WORLDS: &[&str] = &[
647    "printf(\"Hello World\")",
648    "std::cout << \"Hello World\"",
649    "DISPLAY \"Hello World\".    .",
650    "printIn(\"Hello World\")",
651    "disp('Hello World')",
652    "System.Console.WriteLine(\"Hello World\")",
653    "console.lof 'Hello World'",
654    "WriteLn('Hello World')",
655    "print('Hello World')",
656    "main = putStrLn \"Hello World\"",
657    "writeln ('Hello, world.')",
658    "puts 'Hello World'",
659    "print(\"Hello World\")",
660    "db    'Hello World', 10, 0",
661    "cat('Hello World')",
662    "println('Hello World')",
663    "echo \"Hello World\"",
664    "System.out.println(\"Hello World\")",
665    "println('Hello World\")",
666    "printfn \"Hello World\"",
667    "(print \"Hello World\")",
668    "console.log(\"Hello World\")",
669    "BEGIN DISPLAY(\"Hello World\") END.",
670    "print \"Hello World\"",
671    "puts \"Hello World\"",
672    "console.log 'Hello World'",
673    "print *, \"Hello World\"",
674    "<h1>Hello World<\\h1>",
675];
676
677fn help_msg(cmdefines: &CommandsRemapConfig) -> String {
678    format!("\x1b[32mYouTube TUI commands\x1b[0m
679
680\x1b[37mfor more visit https://tui.siri.ws/youtube/commands.html\x1b[0m
681
682\x1b[91mUSAGE:\x1b[0m
683    youtube-tui (command)
684
685\x1b[91mINFORMATIONAL:\x1b[0m
686    \x1b[33mhelp\x1b[0m                            Display this message
687    \x1b[33mversion\x1b[0m                         Print version info and exit
688
689\x1b[91mLOADPAGE:
690\x1b[37mloadpage [page] loads the corresponding page\x1b[0m
691    \x1b[33mloadpage popular\x1b[0m                Loads the popular videos page
692    \x1b[33mloadpage trending\x1b[0m               Loads the trending videos page
693    \x1b[33mloadpage watchhistory\x1b[0m           Loads the watch history page
694    \x1b[33mloadpage subscriptions\x1b[0m          Loads the subscriptions page
695    \x1b[33mloadpage bookmarks\x1b[0m              Loads the bookmarks page
696    \x1b[33mloadpage library\x1b[0m                Loads the library (saved items) page
697    \x1b[33mloadpage feed\x1b[0m                   Loads the library (feed) page
698    \x1b[33mloadpage search [query]\x1b[0m         Loads the search page with the given query
699    \x1b[33mloadpage video [identifier]\x1b[0m     Loads the video item page
700    \x1b[33mloadpage playlist [identifier]\x1b[0m  Loads the playlist item page
701    \x1b[33mloadpage channel [identifier]\x1b[0m   Loads the channel item page
702
703\x1b[91mHISTORY:\x1b[0m
704    \x1b[33mhistory back\x1b[0m                    Revert back to previous state
705    \x1b[33mhistory clear\x1b[0m                   Clear all previously saved states, making the current state the original
706
707\x1b[91mUTILITY:\x1b[0m
708    \x1b[33mreload\x1b[0m                          Reloads the current page
709    \x1b[33mreload configs\x1b[0m                  Reload all config files
710    \x1b[33mflush\x1b[0m                           Run all tasks in queue immediately
711    \x1b[33mquit\x1b[0m                            Immediately exit
712    \x1b[33mrun [command]\x1b[0m                   Runs a system command (e.g. `run rm -rf / --no-preserve-root`)
713    \x1b[33mparrun [command]\x1b[0m                Runs a system command non blocking (e.g. `run firefox example.com`)
714    \x1b[33mcopy [text]\x1b[0m                     Copies text to clipboard
715    \x1b[33mkey [keycode] [keymodifier]\x1b[0m     Create a key input event
716    \x1b[33mecho [mode] [message]\x1b[0m           Dispalys a message in message bar, mode: none, success, warn, error, mpv (can be overwritten by mpv player)
717
718\x1b[91mLIBRARY:\x1b[0m
719    \x1b[33mbookmark [id]\x1b[0m                   Bookmark item with ID (item must be already loaded)
720    \x1b[33munmark [id]\x1b[0m                     Remove bookmark item with ID
721    \x1b[33mtogglemark [id]\x1b[0m                 Toggle bookmark status
722    \x1b[33msub/sync [id or url]\x1b[0m            Add channel to subscription, or sync an existing channel
723    \x1b[33munsub [id or url]\x1b[0m               Remove channel from subscription
724    \x1b[33msyncall\x1b[0m                         Sync all subscriptions
725
726\x1b[91mMPV:\x1b[0m
727    \x1b[33mmpv prop [label]\x1b[0m                Gets mpv property
728    \x1b[33mmpv sprop [label] [value]\x1b[0m       Set mpv property
729    \x1b[33mmpv tprop [label] [value]\x1b[0m       Toggle a yes/no property
730    \x1b[33mmpv [command]\x1b[0m                   Runs a libmpv command
731
732\x1b[91mCUSTOM COMMANDS:\x1b[0m
733\x1b[37mdefined in cmdefine.yml\x1b[30m
734{}
735
736\x1b[37mOnly load page and informational commands should be used from command line, the rest can only be used in (`:`) command mode inside the TUI.\x1b[0m", cmdefines.0.iter().map(|(key, value)| format!("   \x1b[33m{: <28}\x1b[0m     `{value}`", key)).collect::<Vec<_>>().join("\n"))
737}