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