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