src/global/functions/run_command.rs
563 lines · 23386 bytes
1use crate::{
2 config::*,
3 global::{functions::*, structs::*, traits::*},
4 load_configs,
5};
6use home::home_dir;
7use std::{
8 env,
9 error::Error,
10 fs,
11 io::Stdout,
12 process::{Command, Stdio},
13};
14use tui::{backend::CrosstermBackend, Terminal};
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 mainconfig = framework.data.global.get::<MainConfig>().unwrap();
365 let image_index = mainconfig.image_index;
366 let download_thumbnails = mainconfig.images.display();
367 let client = framework
368 .data
369 .global
370 .get::<InvidiousClient>()
371 .unwrap()
372 .clone();
373
374 *framework.data.global.get_mut::<Message>().unwrap() =
375 Message::Message(String::from("Syncing..."));
376 terminal.draw(|frame| framework.render(frame)).unwrap();
377
378 let subscriptions = framework.data.global.get_mut::<Subscriptions>().unwrap();
379 match subscriptions.sync_one(&id, &client, image_index, download_thumbnails) {
380 Ok(()) => {
381 *framework.data.global.get_mut::<Message>().unwrap() =
382 Message::Success(String::from("Channel synced"));
383 }
384 Err(e) => {
385 *framework.data.global.get_mut::<Message>().unwrap() =
386 Message::Error(format!("Sync failed: {e}"));
387 }
388 };
389 framework
390 .data
391 .state
392 .get_mut::<Tasks>()
393 .unwrap()
394 .priority
395 .push(Task::RenderAll);
396 }
397 ["unsub", identifier] => {
398 let id = if identifier.len() == 24 {
399 identifier.to_string()
400 } else {
401 let splitted = identifier.split_once("/channel/");
402
403 match splitted {
404 Some((_, actual_stuff)) if actual_stuff.len() >= 24 => {
405 actual_stuff[0..24].to_string()
406 }
407 _ => {
408 *framework.data.global.get_mut::<Message>().unwrap() =
409 Message::Error(String::from("Invalid identifier: no channel ID found"));
410 return;
411 }
412 }
413 };
414
415 if framework
416 .data
417 .global
418 .get_mut::<Subscriptions>()
419 .unwrap()
420 .remove_one(&id)
421 {
422 *framework.data.global.get_mut::<Message>().unwrap() =
423 Message::Success(String::from("Unsubscribed from channel"));
424 } else {
425 *framework.data.global.get_mut::<Message>().unwrap() =
426 Message::Error(String::from("Channel not found in subscriptions"));
427 }
428 framework
429 .data
430 .state
431 .get_mut::<Tasks>()
432 .unwrap()
433 .priority
434 .push(Task::RenderAll);
435 }
436 ["syncall"] => {
437 *framework.data.global.get_mut::<Message>().unwrap() =
438 Message::Message(String::from("Syncing..."));
439 terminal.draw(|frame| framework.render(frame)).unwrap();
440
441 let client = framework
442 .data
443 .global
444 .get::<InvidiousClient>()
445 .unwrap()
446 .clone();
447 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
448 let image_index = mainconfig.image_index;
449 let download_thumbnails = mainconfig.images.display();
450
451 let (success, failed) = framework
452 .data
453 .global
454 .get_mut::<Subscriptions>()
455 .unwrap()
456 .sync(&client, image_index, download_thumbnails);
457
458 *framework.data.global.get_mut::<Message>().unwrap() = Message::Success(format!(
459 "Subscriptions synced: {success} success | {failed} fail"
460 ));
461
462 framework
463 .data
464 .state
465 .get_mut::<Tasks>()
466 .unwrap()
467 .priority
468 .push(Task::RenderAll);
469 }
470 _ => {
471 *framework.data.global.get_mut::<Message>().unwrap() =
472 Message::Error(format!("Unknown command: `{}`", command.join(" ")));
473 }
474 }
475}
476
477const HELLO_WORLDS: &[&str] = &[
478 "printf(\"Hello World\")",
479 "std::cout << \"Hello World\"",
480 "DISPLAY \"Hello World\". .",
481 "printIn(\"Hello World\")",
482 "disp('Hello World')",
483 "System.Console.WriteLine(\"Hello World\")",
484 "console.lof 'Hello World'",
485 "WriteLn('Hello World')",
486 "print('Hello World')",
487 "main = putStrLn \"Hello World\"",
488 "writeln ('Hello, world.')",
489 "puts 'Hello World'",
490 "print(\"Hello World\")",
491 "db 'Hello World', 10, 0",
492 "cat('Hello World')",
493 "println('Hello World')",
494 "echo \"Hello World\"",
495 "System.out.println(\"Hello World\")",
496 "println('Hello World\")",
497 "printfn \"Hello World\"",
498 "(print \"Hello World\")",
499 "console.log(\"Hello World\")",
500 "BEGIN DISPLAY(\"Hello World\") END.",
501 "print \"Hello World\"",
502 "puts \"Hello World\"",
503 "console.log 'Hello World'",
504 "print *, \"Hello World\"",
505 "<h1>Hello World<\\h1>",
506];
507
508const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
509
510\x1b[37mfor more visit https://siriusmart.github.io/youtube-tui/commands.html\x1b[0m
511
512\x1b[91mUSAGE:\x1b[0m
513 youtube-tui (command)
514
515\x1b[91mINFORMATIONAL:\x1b[0m
516 \x1b[33mhelp\x1b[0m Display this message
517 \x1b[33mversion\x1b[0m Print version info and exit
518
519\x1b[91mLOADPAGE:
520\x1b[37mloadpage [page] loads the corresponding page\x1b[0m
521 \x1b[33mloadpage popular\x1b[0m Loads the popular videos page
522 \x1b[33mloadpage trending\x1b[0m Loads the trending videos page
523 \x1b[33mloadpage watchhistory\x1b[0m Loads the watch history page
524 \x1b[33mloadpage subscriptions\x1b[0m Loads the subscriptions page
525 \x1b[33mloadpage bookmarks\x1b[0m Loads the bookmarks page
526 \x1b[33mloadpage library\x1b[0m Loads the library (saved items) page
527 \x1b[33mloadpage feed\x1b[0m Loads the library (feed) page
528 \x1b[33mloadpage search [query]\x1b[0m Loads the search page with the given query
529 \x1b[33mloadpage video [identifier]\x1b[0m Loads the video item page
530 \x1b[33mloadpage playlist [identifier]\x1b[0m Loads the playlist item page
531 \x1b[33mloadpage channel [identifier]\x1b[0m Loads the channel item page
532
533\x1b[91mHISTORY:\x1b[0m
534 \x1b[33mhistory back\x1b[0m Revert back to previous state
535 \x1b[33mhistory clear\x1b[0m Clear all previously saved states, making the current state the original
536
537\x1b[91mUTILITY:\x1b[0m
538 \x1b[33mreload\x1b[0m Reloads the current page
539 \x1b[33mreload configs\x1b[0m Reload all config files
540 \x1b[33mflush\x1b[0m Run all tasks in queue immediately
541 \x1b[33mquit\x1b[0m Immediately exit
542 \x1b[33mrun [command]\x1b[0m Runs a system command (e.g. `run rm -rf / --no-preserve-root`)
543 \x1b[33mparrun [command]\x1b[0m Runs a system command non blocking (e.g. `run firefox example.com`)
544 \x1b[33mcopy [text]\x1b[0m Copies text to clipboard
545
546\x1b[91mLIBRARY:\x1b[0m
547 \x1b[33mbookmark [id]\x1b[0m Bookmark item with ID (item must be already loaded)
548 \x1b[33munmark [id]\x1b[0m Remove bookmark item with ID
549 \x1b[33mtogglemark [id]\x1b[0m Toggle bookmark status
550 \x1b[33msub/sync [id or url]\x1b[0m Add channel to subscription, or sync an existing channel
551 \x1b[33munsub [id or url]\x1b[0m Remove channel from subscription
552 \x1b[33msyncall\x1b[0m Sync all subscriptions
553
554\x1b[91mALT:\x1b[0m
555\x1b[37malts links back to the original command\x1b[30m
556 \x1b[33m[page] (additional options)\x1b[0m `loadpage [page]`
557 \x1b[33mback\x1b[0m `history back`
558 \x1b[33mr\x1b[0m `reload`
559 \x1b[33mreload/r config/configs\x1b[0m `reload configs`
560 \x1b[33mq, exit, x\x1b[0m `quit`
561 \x1b[33mcp [text]\x1b[0m `copy [text]`
562
563\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";