Commit 2512b334b4

2512b334b421431b5e8577ab9c3031350fcd71bd

parent: 2b3fdf3bab

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-06-26 18:34 UTC

Commands to run can be edited, keybindings.yml

Layout: unified · split

Cargo.lock +1 −1
@@ -1716,7 +1716,7 @@ dependencies = [
17161716
17171717[[package]]
17181718name = "youtube-tui"
1719version = "0.3.0"
1719version = "0.4.0"
17201720dependencies = [
17211721 "chrono",
17221722 "crossterm",
Cargo.toml +1 −1
@@ -1,6 +1,6 @@
11[package]
22name = "youtube-tui"
3version = "0.3.1"
3version = "0.4.0"
44edition = "2021"
55authors = ["Siriusmart <siriusmart@tuta.io>"]
66description = "An aesthetically pleasing YouTube TUI written in Rust"
README.md +38 −6
@@ -14,11 +14,14 @@ YouTube TUI is a text user interface that provides a clean UI for browsing YouTu
1414
1515This program is being actively developed and there will be new features coming up every commit.
1616
17![Screenshot](https://cdn.discordapp.com/attachments/906941311142219816/990684947830419526/Screenshot_20220626_192433.png)
18
1719> ### What's new in this commit
1820>
19> * Code is being cleaned up but still unreadable
20> * Haven't touched this project for a week because of exams, so I'm just trying to figure out how stuff works again
21> * Just a little save stat before I overhaul the configs and how it's handled
21> * More code cleanup
22> * Commands to be ran in Item Info page can be changed, items can be add/removed (in `page_commands.yml`)
23> * Keybindings can be created (VIM keybindings are included in default config)
24> * Config soft update (tries to add new options to the config, and if parsing config failed the config will be backed up and a new one will be generated)
2225
2326## Installation
2427
@@ -35,6 +38,16 @@ git clone https://github.com/sirusmart/youtube-tui && cd youtube-tui && cargo bu
3538
3639The binary is located at `./target/release/youtube-tui`, go move it to other locations so that you can launch the program with `youtube-tui` command.
3740
41> ### Dependencies
42>
43> This program does not requires any dependencies, but it is suggested these three things on your system that can be launched via command:
44>
45> 1. A video player (Default to `mpv`)
46> 2. A terminal emulator (Defaults to `konsole`)
47> 3. A YouTube downloader (Defaults to `yt-dlp`, strongly suggest NOT to use `youtube-dl` because it is now very slow)
48>
49> None of these dependencies are required as you can change them in config (in `commands.yml`)
50
3851## Usage
3952
4053### To launch
@@ -47,7 +60,7 @@ youtube-tui # or path to the binary
4760
4861|Key|What does it do|
4962|---|---|
50|Arrow keys|Move in corresponding direction|
63|Arrow/Vim keys|Move in corresponding direction|
5164|Right arrow|Move cursor right
5265|Enter|Select/Launch|
5366|Q|Quit the program|
@@ -56,6 +69,24 @@ youtube-tui # or path to the binary
5669>
5770> These keys only work when nothing is selected. When something is selected, your key presses are passed directly to the "object" you've selected. Press escape (Esc) if you want to deselect.
5871
72### Config
73
74All config files are loacted at `~/.config/youtube-tui/`, will write documentations for that later
75
76## Todo (First piority on top)
77
78* Put hard coded options into config files
79* User manual + documentations
80* Channel search and channel video sort
81* Recommended videos
82
83## Help needed
84
85Guys please I need help I'm kinda bad at coding tbh, these are stuff that I need help with
86
87* Publishing to the AUR
88* Printing full resolution images to the terminal with Sixels
89
5990## Credits
6091
6192* [ytfzf](https://github.com/pystardust/ytfzf) by [pystardust](https://github.com/pystardust) - The TUI I used to watch YouTube, gave me an idea how this program is going to work
@@ -64,6 +95,7 @@ youtube-tui # or path to the binary
6495
6596
6697... and of course, credits to myself for not having the ability to read the docs for ytfzf and decided to make my own instead.
67## Bug reports
6898
69If there is an issue with this program, please open an issue on GitHub, thank you :D
99## Anything Missing?
100
101If there is a bug or you got a nice idea on what can be added to this program, feel free to open a GitHub issue. Thx :D
src/app/app.rs +25 −17
@@ -19,7 +19,7 @@ use tui::{
1919};
2020
2121use super::{
22 config::Config,
22 config::{Action, Config},
2323 pages::{channel::Channel, item_info::ItemInfo, search::Search},
2424};
2525
@@ -45,13 +45,14 @@ pub struct App {
4545
4646impl Default for App {
4747 fn default() -> Self {
48 let config = Config::load().unwrap();
4849 let state = MainMenu::default();
4950 let selectable = App::selectable(&state);
5051 Self {
5152 page: Page::default(),
5253 state,
5354 selectable,
54 client: Client::new(String::from("https://vid.puffyan.us")),
55 client: Client::new(config.main.server_url.clone()),
5556 selected: None,
5657 hover: None,
5758 message: Arc::new(Mutex::new(None)),
@@ -59,7 +60,7 @@ impl Default for App {
5960 render: true,
6061 popup_focus: false,
6162 history: Vec::new(),
62 config: Config::load().unwrap(),
63 config,
6364 watch_history: WatchHistory::load(),
6465 search_settings: SearchSettings::default(),
6566 search_text: String::new(),
@@ -94,8 +95,10 @@ impl App {
9495 }
9596
9697 pub fn key_input(mut self, key: KeyCode) -> App {
98 let action = self.config.keybindings.0.get(&key);
99
97100 if let Some((x, y)) = self.selected {
98 if key != KeyCode::Esc {
101 if action != Some(&Action::Deselect) {
99102 let mut item = self.state[y].items[x].item.clone();
100103 let updated;
101104 (updated, self) = item.key_input(key, self);
@@ -107,8 +110,13 @@ impl App {
107110 }
108111 }
109112
110 match key {
111 KeyCode::Enter => {
113 let action = match action {
114 Some(action) => *action,
115 None => return self,
116 };
117
118 match action {
119 Action::Select => {
112120 if self.hover.is_some() && self.selected.is_none() {
113121 let (mut x, mut y) = self.hover.unwrap();
114122 (x, y) = self.selectable[y][x];
@@ -130,7 +138,7 @@ impl App {
130138 return self;
131139 }
132140 }
133 KeyCode::Esc => {
141 Action::Deselect => {
134142 if self.selected.is_some() {
135143 self.selected = None;
136144 self.popup_focus = false;
@@ -142,8 +150,8 @@ impl App {
142150 }
143151
144152 match &mut self.hover {
145 Some((x, y)) => match key {
146 KeyCode::Up => {
153 Some((x, y)) => match action {
154 Action::Up => {
147155 if *y > 0 {
148156 let temp_y = *y - 1;
149157 if *x > self.selectable[temp_y].len() {
@@ -158,7 +166,7 @@ impl App {
158166 }
159167 }
160168 }
161 KeyCode::Down => {
169 Action::Down => {
162170 if *y < self.selectable.len() - 1 {
163171 *y += 1;
164172 if *x > self.selectable[*y].len() - 1 {
@@ -167,13 +175,13 @@ impl App {
167175 }
168176 }
169177
170 KeyCode::Left => {
178 Action::Left => {
171179 if *x > 0 {
172180 *x -= 1;
173181 }
174182 }
175183
176 KeyCode::Right => {
184 Action::Right => {
177185 if *x < self.selectable[*y].len() - 1 {
178186 *x += 1;
179187 }
@@ -181,17 +189,17 @@ impl App {
181189
182190 _ => {}
183191 },
184 None => match key {
185 KeyCode::Up => {
192 None => match action {
193 Action::Up => {
186194 self.hover = Some((0, 0));
187195 }
188 KeyCode::Down => {
196 Action::Down => {
189197 self.hover = Some((0, self.selectable.len() - 1));
190198 }
191 KeyCode::Left => {
199 Action::Left => {
192200 self.hover = Some((0, 0));
193201 }
194 KeyCode::Right => {
202 Action::Right => {
195203 self.hover = Some((0, self.selectable.len() - 1));
196204 }
197205 _ => {}
src/app/config/commands.rs +140 −213
@@ -1,240 +1,167 @@
1use std::{
2 error::Error,
3 fs::{self, OpenOptions},
4 io::Write,
5};
6
71use serde::{Deserialize, Serialize};
2use std::{collections::HashMap, thread};
83
9use crate::functions::insert_vec;
10
11use super::{Config, EnvVar};
12
13#[derive(Debug, Clone, Deserialize, Serialize)]
14pub struct CommandsConfigTransitional {
15 video_player: Option<CommandConfig>,
16 audio_player: Option<CommandConfig>,
17 image_viewer: Option<CommandConfig>,
18 video_downloader: Option<CommandConfig>,
19 audio_downloader: Option<CommandConfig>,
20 terminal: Option<CommandConfig>,
21 playlist_audio_all: Option<CommandConfig>,
22 playlist_video_all: Option<CommandConfig>,
23 playlist_shuffle_audio_all: Option<CommandConfig>,
24 download_all_audio: Option<CommandConfig>,
25 download_all_video: Option<CommandConfig>,
26}
27
28#[derive(Clone, Debug, Serialize, Deserialize)]
29pub struct CommandsConfig {
30 pub video_player: CommandConfig,
31 pub audio_player: CommandConfig,
32 pub image_viewer: CommandConfig,
33 pub video_downloader: CommandConfig,
34 pub audio_downloader: CommandConfig,
35 pub terminal: CommandConfig,
36 pub playlist_audio_all: CommandConfig,
37 pub playlist_video_all: CommandConfig,
38 pub playlist_shuffle_audio_all: CommandConfig,
39 pub download_all_audio: CommandConfig,
40 pub download_all_video: CommandConfig,
41}
4use crate::traits::ConfigItem;
425
43#[derive(Clone, Debug, Serialize, Deserialize)]
44pub struct CommandConfig {
45 pub command: String,
46 pub open_in_console: bool,
6#[derive(Serialize, Deserialize, Clone, Debug)]
7pub struct Command {
478 pub args: Vec<String>,
9 pub message: String,
4810}
4911
50impl CommandConfig {
51 pub fn as_vec(&self) -> Vec<String> {
52 let mut args = self.args.clone();
53 args.insert(0, self.command.clone());
54 args
12#[derive(Serialize, Deserialize, Clone, Debug)]
13pub struct CommandsConfig(pub HashMap<String, Command>);
14
15impl Command {
16 pub fn as_vec(&self, variables: &HashMap<String, String>) -> Result<Vec<String>, String> {
17 let mut out = Vec::new();
18
19 for arg in self.args.iter() {
20 out.push(match check_arg(arg) {
21 ArgType::Normal(s) => s,
22 ArgType::Variable(s) => match variables.get(s) {
23 Some(s) => s.to_string(),
24 None => return Err(s.to_string()),
25 },
26 })
27 }
28
29 Ok(out)
5530 }
5631
57 pub fn as_command_vec(self, env: EnvVar, config: &Config) -> Result<Vec<String>, ()> {
58 let mut out;
59 if self.open_in_console {
60 out = config.commands.terminal.as_vec();
61 let index = match out.iter().position(|x| x == "{command}") {
62 Some(index) => {
63 out.swap_remove(index);
64 index
65 }
66 None => out.len(),
67 };
68
69 insert_vec(&mut out, self.as_vec(), index);
70 } else {
71 out = self.as_vec();
32 pub fn run_command(&self, variables: &HashMap<String, String>) -> Option<String> {
33 let mut args = match self.as_vec(variables) {
34 Ok(args) => args,
35 Err(s) => return Some(s),
7236 }
73
74 for x in out.iter_mut() {
75 match x.as_str() {
76 "{url}" => {
77 if let Some(url) = &env.url {
78 *x = url.clone();
79 } else {
80 return Err(());
81 }
82 }
83
84 "{video_save_location}" => {
85 *x = config.main.yt_dl.video_path.clone();
86 }
87
88 "{audio_save_location}" => {
89 *x = config.main.yt_dl.audio_path.clone();
90 }
91
92 _ => {}
37 .into_iter();
38 thread::spawn(move || {
39 let mut command = std::process::Command::new(args.next().unwrap());
40 for arg in args {
41 command.arg(arg);
9342 }
94 }
9543
96 Ok(out)
44 let _ = command.output();
45 });
46
47 None
9748 }
9849}
9950
10051impl Default for CommandsConfig {
10152 fn default() -> Self {
102 Self {
103 video_player: CommandConfig {
104 command: String::from("mpv"),
105 open_in_console: false,
106 args: vec![String::from("--no-terminal"), String::from("{url}")],
107 },
108 audio_player: CommandConfig {
109 command: String::from("mpv"),
110 open_in_console: true,
111 args: vec![String::from("--no-video"), String::from("{url}")],
112 },
113 image_viewer: CommandConfig {
114 command: String::from("mpv"),
115 open_in_console: false,
116 args: vec![String::from("{url}"), String::from("--no-terminal")],
117 },
118 video_downloader: CommandConfig {
119 command: String::from("yt-dlp"),
120 open_in_console: true,
121 args: vec![
122 String::from("{url}"),
123 String::from("-o"),
124 String::from("{video_save_location}"),
125 ],
126 },
127 audio_downloader: CommandConfig {
128 command: String::from("yt-dlp"),
129 open_in_console: true,
130 args: vec![
131 String::from("{url}"),
132 String::from("-o"),
133 String::from("{audio_save_location}"),
134 String::from("-x"),
135 ],
136 },
137 terminal: CommandConfig {
138 command: String::from("konsole"),
139 open_in_console: false,
140 args: vec![String::from("-e"), String::from("{command}")],
141 },
142 playlist_audio_all: CommandConfig {
143 command: String::from("mpv"),
144 open_in_console: true,
145 args: vec![String::from("--no-video"), String::from("{url}")],
146 },
147 playlist_video_all: CommandConfig {
148 command: String::from("mpv"),
149 open_in_console: false,
150 args: vec![String::from("{url}"), String::from("--no-terminal")],
151 },
152 playlist_shuffle_audio_all: CommandConfig {
153 command: String::from("mpv"),
154 open_in_console: true,
155 args: vec![
156 String::from("--no-video"),
157 String::from("{url}"),
158 String::from("--shuffle"),
159 ],
160 },
161 download_all_audio: CommandConfig {
162 command: String::from("yt-dlp"),
163 open_in_console: true,
164 args: vec![
165 String::from("{url}"),
166 String::from("-o"),
167 String::from("{audio_save_location}"),
168 String::from("-x"),
169 ],
170 },
171 download_all_video: CommandConfig {
172 command: String::from("yt-dlp"),
173 open_in_console: true,
174 args: vec![
175 String::from("{url}"),
176 String::from("-o"),
177 String::from("{video_save_location}"),
178 ],
179 },
180 }
181 }
182}
183
184impl From<CommandsConfigTransitional> for CommandsConfig {
185 fn from(original: CommandsConfigTransitional) -> CommandsConfig {
186 let mut out = Self::default();
187
188 if let Some(video_player) = original.video_player {
189 out.video_player = video_player;
190 }
191
192 if let Some(audio_player) = original.audio_player {
193 out.audio_player = audio_player;
194 }
195
196 if let Some(image_viewer) = original.image_viewer {
197 out.image_viewer = image_viewer;
198 }
199
200 if let Some(video_downloader) = original.video_downloader {
201 out.video_downloader = video_downloader;
202 }
203
204 if let Some(audio_downloader) = original.audio_downloader {
205 out.audio_downloader = audio_downloader;
206 }
207
208 if let Some(terminal) = original.terminal {
209 out.terminal = terminal;
210 }
53 let mut out = Self::blank();
54
55 out.insert(
56 "video_player",
57 vec!["mpv", "{embed_url}", "--no-terminal"],
58 "Launched mpv",
59 );
60 out.insert(
61 "audio_player",
62 vec!["konsole", "-e", "mpv", "{embed_url}", "--no-video"],
63 "Opened mpv in new konsole window",
64 );
65 out.insert(
66 "audio_playlist_shuffle",
67 vec![
68 "konsole",
69 "-e",
70 "mpv",
71 "{embed_url}",
72 "--no-video",
73 "--shuffle",
74 ],
75 "Opened mpv in new konsole window",
76 );
77 out.insert(
78 "audio_playlist_loop",
79 vec![
80 "konsole",
81 "-e",
82 "mpv",
83 "{embed_url}",
84 "--no-video",
85 "--loop-playlist=inf",
86 ],
87 "Opened mpv in new konsole window",
88 );
89 out.insert(
90 "audio_playlist_shuffle_loop",
91 vec![
92 "konsole",
93 "-e",
94 "mpv",
95 "{embed_url}",
96 "--no-video",
97 "--loop-playlist=inf",
98 "--shuffle",
99 ],
100 "Opened mpv in new konsole window",
101 );
102 out.insert(
103 "video_downloader",
104 vec![
105 "konsole",
106 "-e",
107 "yt-dlp",
108 "{embed_url}",
109 "-o",
110 "{download_location}",
111 ],
112 "Download has started",
113 );
114
115 out.insert(
116 "audio_downloader",
117 vec![
118 "konsole",
119 "-e",
120 "yt-dlp",
121 "{embed_url}",
122 "-o",
123 "{download_location}",
124 "-x",
125 ],
126 "Download has started",
127 );
211128
212129 out
213130 }
214131}
215132
216133impl CommandsConfig {
217 pub fn load() -> Result<Self, Box<dyn Error>> {
218 let mut config = home::home_dir().expect("Cannot get your home directory");
219 let mut commands = CommandsConfig::default();
220 config.push(".config");
221 config.push("youtube-tui");
222 config.push("commands.yml");
223
224 if config.exists() {
225 let content = fs::read_to_string(config.as_os_str())?;
226 let commands_transitional: CommandsConfigTransitional = serde_yaml::from_str(&content)?;
227 commands = commands_transitional.into();
228 }
134 fn blank() -> Self {
135 Self(HashMap::default())
136 }
229137
230 let mut file = OpenOptions::new()
231 .write(true)
232 .truncate(true)
233 .create(true)
234 .open(config.as_os_str())?;
138 fn insert(&mut self, label: &str, command: Vec<&str>, msg: &str) {
139 self.0.insert(
140 label.to_string(),
141 Command {
142 args: command
143 .into_iter()
144 .map(|item| item.to_string())
145 .collect::<Vec<_>>(),
146 message: msg.to_string(),
147 },
148 );
149 }
150}
235151
236 write!(file, "{}", serde_yaml::to_string(&commands)?)?;
152impl ConfigItem<'_> for CommandsConfig {
153 type Struct = CommandsConfig;
154 const FILE_NAME: &'static str = "commands.yml";
155}
156enum ArgType<'a> {
157 Normal(String),
158 Variable(&'a str),
159}
237160
238 Ok(commands)
161fn check_arg(s: &str) -> ArgType {
162 if s.starts_with('{') && s.ends_with('}') {
163 ArgType::Variable(&s[1..s.len() - 1])
164 } else {
165 ArgType::Normal(s.to_string())
239166 }
240167}
src/app/config/config.rs +8 −1
@@ -1,11 +1,14 @@
11use std::error::Error;
22
3use super::{commands::CommandsConfig, MainConfig};
3use super::{commands::CommandsConfig, MainConfig, PageCommandsConfig, KeybindingsConfig};
4use crate::traits::ConfigItem;
45
56#[derive(Clone, Debug)]
67pub struct Config {
78 pub commands: CommandsConfig,
89 pub main: MainConfig,
10 pub page_commands: PageCommandsConfig,
11 pub keybindings: KeybindingsConfig,
912}
1013
1114impl Default for Config {
@@ -13,6 +16,8 @@ impl Default for Config {
1316 Self {
1417 commands: CommandsConfig::default(),
1518 main: MainConfig::default(),
19 page_commands: PageCommandsConfig::default(),
20 keybindings: KeybindingsConfig::default(),
1621 }
1722 }
1823}
@@ -22,6 +27,8 @@ impl Config {
2227 Ok(Self {
2328 main: MainConfig::load()?,
2429 commands: CommandsConfig::load()?,
30 page_commands: PageCommandsConfig::load()?,
31 keybindings: KeybindingsConfig::load()?.into(),
2532 })
2633 }
2734}
src/app/config/keybindings.rs added +128
@@ -0,0 +1,128 @@
1use std::collections::HashMap;
2
3use crossterm::event::KeyCode;
4use serde::{Serialize, Deserialize};
5
6use crate::traits::ConfigItem;
7
8#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
9pub enum Action {
10 Up,
11 Down,
12 Left,
13 Right,
14 Select,
15 Deselect,
16 FirstItem,
17 LastItem,
18 Home,
19 Exit,
20 Back,
21 ClearHistory,
22}
23
24#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
25pub enum KeyCodeTransitional {
26 Backspace,
27 Enter,
28 Left,
29 Right,
30 Up,
31 Down,
32 Home,
33 End,
34 PageUp,
35 PageDown,
36 Tab,
37 BackTab,
38 Delete,
39 Insert,
40 F(u8),
41 Char(char),
42 Null,
43 Esc,
44}
45
46impl Into<KeyCode> for KeyCodeTransitional {
47 fn into(self) -> KeyCode {
48 match self {
49 Self::Backspace => KeyCode::Backspace,
50 Self::Enter => KeyCode::Enter,
51 Self::Left => KeyCode::Left,
52 Self::Right => KeyCode::Right,
53 Self::Up => KeyCode::Up,
54 Self::Down => KeyCode::Down,
55 Self::Home => KeyCode::Home,
56 Self::End => KeyCode::End,
57 Self::PageUp => KeyCode::PageUp,
58 Self::PageDown => KeyCode::PageDown,
59 Self::Tab => KeyCode::Tab,
60 Self::BackTab => KeyCode::BackTab,
61 Self::Delete => KeyCode::Delete,
62 Self::Insert => KeyCode::Insert,
63 Self::F(n) => KeyCode::F(n),
64 Self::Char(c) => KeyCode::Char(c),
65 Self::Null => KeyCode::Null,
66 Self::Esc => KeyCode::Esc,
67 }
68 }
69}
70
71impl Into<KeybindingsConfig> for KeybindingsConfigTransitional {
72 fn into(self) -> KeybindingsConfig {
73 let mut out = HashMap::default();
74
75 for (k, v) in self.0.into_iter() {
76 out.insert(k.into(), v);
77 }
78
79 KeybindingsConfig(out)
80 }
81}
82
83#[derive(Serialize, Deserialize, Debug, Clone)]
84pub struct KeybindingsConfigTransitional (pub HashMap<KeyCodeTransitional, Action>);
85
86impl Default for KeybindingsConfigTransitional {
87 fn default() -> Self {
88 let mut out = HashMap::default();
89
90 out.insert(KeyCodeTransitional::Up, Action::Up);
91 out.insert(KeyCodeTransitional::Down, Action::Down);
92 out.insert(KeyCodeTransitional::Left, Action::Left);
93 out.insert(KeyCodeTransitional::Right, Action::Right);
94
95 out.insert(KeyCodeTransitional::Char('h'), Action::Left);
96 out.insert(KeyCodeTransitional::Char('j'), Action::Down);
97 out.insert(KeyCodeTransitional::Char('k'), Action::Up);
98 out.insert(KeyCodeTransitional::Char('l'), Action::Right);
99
100 out.insert(KeyCodeTransitional::PageUp, Action::FirstItem);
101 out.insert(KeyCodeTransitional::PageDown, Action::LastItem);
102
103 out.insert(KeyCodeTransitional::Enter, Action::Select);
104 out.insert(KeyCodeTransitional::Esc, Action::Deselect);
105 out.insert(KeyCodeTransitional::Char('q'), Action::Exit);
106
107 out.insert(KeyCodeTransitional::Home, Action::Home);
108 out.insert(KeyCodeTransitional::Backspace, Action::Back);
109 out.insert(KeyCodeTransitional::End, Action::ClearHistory);
110
111 Self(out)
112 }
113}
114
115impl Default for KeybindingsConfig {
116 fn default() -> Self {
117 KeybindingsConfigTransitional::default().into()
118 }
119}
120
121#[derive(Debug, Clone)]
122pub struct KeybindingsConfig (pub HashMap<KeyCode, Action>);
123
124
125impl ConfigItem<'_> for KeybindingsConfig {
126 type Struct = KeybindingsConfigTransitional;
127 const FILE_NAME: &'static str = "keybindings.yml";
128}
src/app/config/main.rs +31 −66
@@ -1,85 +1,50 @@
1use std::{
2 error::Error,
3 fs::{self, OpenOptions},
4 io::Write,
5};
1use std::collections::HashMap;
62
3use crate::traits::ConfigItem;
74use serde::{Deserialize, Serialize};
85
9#[derive(Clone, Debug, Serialize, Deserialize)]
10pub struct MainConfigTransitional {
11 pub yt_dl: Option<YtDlConfig>,
12 pub max_watch_history: Option<usize>,
6fn max_watch_history_default() -> usize {
7 50
138}
149
15#[derive(Clone, Debug, Serialize, Deserialize)]
16pub struct MainConfig {
17 pub yt_dl: YtDlConfig,
18 pub max_watch_history: usize,
10fn server_url_default() -> String {
11 String::from("https://vid.puffyan.us")
1912}
2013
21impl Default for MainConfig {
22 fn default() -> Self {
23 Self {
24 yt_dl: YtDlConfig::default(),
25 max_watch_history: 50,
26 }
27 }
14fn env_default() -> HashMap<String, String> {
15 let mut out = HashMap::default();
16
17 out.insert(
18 String::from("download_location"),
19 String::from("~/Downloads/%(title)s.%(ext)s"),
20 );
21
22 out
2823}
2924
3025#[derive(Clone, Debug, Serialize, Deserialize)]
31pub struct YtDlConfig {
32 pub video_path: String,
33 pub audio_path: String,
26pub struct MainConfig {
27 #[serde(default = "max_watch_history_default")]
28 pub max_watch_history: usize,
29
30 #[serde(default = "server_url_default")]
31 pub server_url: String,
32
33 #[serde(default = "env_default")]
34 pub env: HashMap<String, String>,
3435}
3536
36impl Default for YtDlConfig {
37impl Default for MainConfig {
3738 fn default() -> Self {
3839 Self {
39 video_path: String::from("~/Downloads/%(title)s.%(ext)s"),
40 audio_path: String::from("~/Downloads/%(title)s.%(ext)s"),
40 max_watch_history: max_watch_history_default(),
41 server_url: server_url_default(),
42 env: env_default(),
4143 }
4244 }
4345}
4446
45impl From<MainConfigTransitional> for MainConfig {
46 fn from(config: MainConfigTransitional) -> Self {
47 let mut out = MainConfig::default();
48
49 if let Some(yt_dl) = config.yt_dl {
50 out.yt_dl = yt_dl;
51 }
52
53 if let Some(max_watch_history) = config.max_watch_history {
54 out.max_watch_history = max_watch_history;
55 }
56
57 out
58 }
59}
60
61impl MainConfig {
62 pub fn load() -> Result<Self, Box<dyn Error>> {
63 let mut config = home::home_dir().expect("Cannot get your home directory");
64 let mut main = MainConfig::default();
65 config.push(".config");
66 config.push("youtube-tui");
67 config.push("main.yml");
68
69 if config.exists() {
70 let content = fs::read_to_string(config.as_os_str())?;
71 let main_transitional: MainConfigTransitional = serde_yaml::from_str(&content)?;
72 main = main_transitional.into();
73 }
74
75 let mut file = OpenOptions::new()
76 .write(true)
77 .truncate(true)
78 .create(true)
79 .open(config.as_os_str())?;
80
81 write!(file, "{}", serde_yaml::to_string(&main)?)?;
82
83 Ok(main)
84 }
47impl ConfigItem<'_> for MainConfig {
48 type Struct = MainConfig;
49 const FILE_NAME: &'static str = "main.yml";
8550}
src/app/config/mod.rs +6
@@ -5,3 +5,9 @@ pub use config::*;
55
66mod main;
77pub use main::*;
8
9mod page_commands;
10pub use page_commands::*;
11
12mod keybindings;
13pub use keybindings::*;
src/app/config/page_commands.rs added +72
@@ -0,0 +1,72 @@
1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5use crate::traits::ConfigItem;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct PageCommandsConfig(pub HashMap<String, Vec<PageCommand>>);
9
10impl PageCommandsConfig {
11 fn blank() -> Self {
12 Self(HashMap::default())
13 }
14}
15
16impl Default for PageCommandsConfig {
17 fn default() -> Self {
18 let mut out = Self::blank();
19
20 out.0.insert(
21 String::from("item_info:video"),
22 vec![
23 PageCommand::from("Watch video", "video_player"),
24 PageCommand::from("Play audio", "audio_player"),
25 PageCommand::from("Download video", "video_downloader"),
26 PageCommand::from("Download audio", "audio_downloader"),
27 PageCommand::from("Visit channel", "{goto_channel}"),
28 PageCommand::from("{mode}", "{toggle_mode}"),
29 ],
30 );
31
32 out.0.insert(
33 String::from("item_info:playlist"),
34 vec![
35 PageCommand::from("Switch view", "{switch_view}"),
36 PageCommand::from("Watch all", "video_player"),
37 PageCommand::from("Play all audio", "audio_player"),
38 PageCommand::from("Shuffle play all audio", "audio_playlist_shuffle"),
39 PageCommand::from(
40 "Shuffle play all audio (loop)",
41 "audio_playlist_shuffle_loop",
42 ),
43 PageCommand::from("Download all video", "video_downloader"),
44 PageCommand::from("Download all audio", "audio_downloader"),
45 PageCommand::from("Visit channel", "{goto_channel}"),
46 PageCommand::from("{mode}", "{toggle_mode}"),
47 ],
48 );
49
50 out
51 }
52}
53
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct PageCommand {
56 pub label: String,
57 pub command: String,
58}
59
60impl PageCommand {
61 fn from(label: &str, command: &str) -> Self {
62 Self {
63 label: label.to_string(),
64 command: command.to_string(),
65 }
66 }
67}
68
69impl ConfigItem<'_> for PageCommandsConfig {
70 type Struct = PageCommandsConfig;
71 const FILE_NAME: &'static str = "page_commands.yml";
72}
src/app/pages/channel.rs +18 −13
@@ -10,7 +10,7 @@ use tui::{
1010};
1111
1212use crate::{
13 app::app::App,
13 app::{app::App, config::Action},
1414 functions::download_all_thumbnails,
1515 structs::{
1616 FullChannel, Item, ListItem, MiniPlayList, MiniVideo, Page, Row, RowItem, WatchHistory,
@@ -294,22 +294,27 @@ impl ItemTrait for ChannelItem {
294294 }
295295
296296 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
297 let action = match app.config.keybindings.0.get(&key) {
298 Some(action) => action,
299 None => return (false, app),
300 };
301
297302 match self {
298303 ChannelItem::InfoDisplay(displayitem) => match displayitem {
299 ChannelDisplayItem::Videos(videos, textlist) => match key {
300 KeyCode::Up => {
304 ChannelDisplayItem::Videos(videos, textlist) => match action {
305 Action::Up => {
301306 textlist.up();
302307 }
303 KeyCode::Down => {
308 Action::Down => {
304309 textlist.down();
305310 }
306 KeyCode::PageUp => {
311 Action::FirstItem => {
307312 textlist.selected = 0;
308313 }
309 KeyCode::PageDown => {
314 Action::LastItem => {
310315 textlist.selected = textlist.items.len() - 1;
311316 }
312 KeyCode::Enter => {
317 Action::Select => {
313318 let state = ItemInfo::default();
314319 let mut history = app.history.clone();
315320 history.push(app.into());
@@ -330,20 +335,20 @@ impl ItemTrait for ChannelItem {
330335 _ => {}
331336 },
332337
333 ChannelDisplayItem::Playlists(playlists, textlist) => match key {
334 KeyCode::Up => {
338 ChannelDisplayItem::Playlists(playlists, textlist) => match action {
339 Action::Up => {
335340 textlist.up();
336341 }
337 KeyCode::Down => {
342 Action::Down => {
338343 textlist.down();
339344 }
340 KeyCode::PageUp => {
345 Action::FirstItem => {
341346 textlist.selected = 0;
342347 }
343 KeyCode::PageDown => {
348 Action::LastItem => {
344349 textlist.selected = textlist.items.len() - 1;
345350 }
346 KeyCode::Enter => {
351 Action::Select => {
347352 let state = ItemInfo::default();
348353 let mut history = app.history.clone();
349354 history.push(app.into());
src/app/pages/global.rs +2 −11
@@ -26,7 +26,7 @@ pub enum GlobalItem {
2626 MessageBar,
2727}
2828
29#[derive(Debug, Clone, Copy)]
29#[derive(Debug, Clone, Copy, PartialEq)]
3030pub enum Mode {
3131 Youtube,
3232 Invidious,
@@ -109,7 +109,7 @@ impl ItemTrait for GlobalItem {
109109 _ => {}
110110 },
111111 GlobalItem::SearchSettings => {
112 app.search_settings.key_input(key);
112 app.search_settings.key_input(key, &app.config);
113113 }
114114 _ => {}
115115 }
@@ -118,15 +118,6 @@ impl ItemTrait for GlobalItem {
118118 }
119119
120120 fn render_item<B: Backend>(
121 // &self,
122 // frame: &mut Frame<B>,
123 // rect: Rect,
124 // selected: bool,
125 // hover: bool,
126 // popup_render: bool,
127 // message: &Option<String>,
128 // search_settings: &mut SearchSettings,
129 // search_text: &String,
130121 &self,
131122 frame: &mut Frame<B>,
132123 rect: Rect,
src/app/pages/item_info.rs +144 −482
@@ -1,13 +1,14 @@
11use std::{
22 collections::LinkedList,
33 error::Error,
4 process::Command,
5 sync::{Arc, Mutex},
6 thread,
74};
85
96use crate::{
10 app::{app::App, config::EnvVar, pages::global::*},
7 app::{
8 app::App,
9 config::{Action, PageCommand},
10 pages::{channel::*, global::*},
11 },
1112 functions::download_all_thumbnails,
1213 structs::{FullPlayList, FullVideo, Item, ListItem, Page, Row, RowItem, WatchHistory},
1314 traits::{ItemTrait, PageTrait},
@@ -21,10 +22,7 @@ use tui::{
2122 Frame,
2223};
2324
24use super::{
25 channel::{Channel, ChannelPage},
26 global::GlobalItem,
27};
25use super::global::GlobalItem;
2826
2927#[derive(Debug, Clone)]
3028pub enum ItemInfoItem {
@@ -38,6 +36,7 @@ pub struct VideoItemInfo {
3836 video: FullVideo,
3937 list: TextList,
4038 mode: Mode,
39 commands: Vec<PageCommand>,
4140}
4241
4342#[derive(Debug, Clone)]
@@ -47,6 +46,7 @@ pub struct PlayListItemInfo {
4746 playlist_view_list: TextList,
4847 display_view: PlayListDisplayView,
4948 mode: Mode,
49 commands: Vec<PageCommand>,
5050}
5151
5252#[derive(Debug, Clone, Copy)]
@@ -76,173 +76,22 @@ impl ItemTrait for ItemInfoItem {
7676 }
7777
7878 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
79 let action = match app.config.keybindings.0.get(&key) {
80 Some(action) => *action,
81 None => return (false, app),
82 };
7983 match self {
80 ItemInfoItem::Video(videoinfo) => match key {
81 KeyCode::Up => videoinfo.list.up(),
82 KeyCode::Down => videoinfo.list.down(),
83 KeyCode::PageUp => videoinfo.list.selected = 0,
84 KeyCode::PageDown => videoinfo.list.selected = videoinfo.list.items.len() - 1,
85 KeyCode::Enter => {
86 if videoinfo.list.selected < 5 {
87 *app.message.lock().unwrap() = Some(String::from("Launched application"));
88 }
89
90 match videoinfo.list.selected {
91 0 => {
92 let command =
93 match app.config.commands.video_player.clone().as_command_vec(
94 EnvVar {
95 url: Some(match videoinfo.mode {
96 Mode::Youtube => {
97 format!(
98 "https://youtu.be/{}",
99 videoinfo.video.video_id
100 )
101 }
102 Mode::Invidious => {
103 format!(
104 "{}/embed/{}",
105 app.client.server, videoinfo.video.video_id
106 )
107 }
108 }),
109 ..Default::default()
110 },
111 &app.config,
112 ) {
113 Ok(command) => command,
114 Err(_) => {
115 *app.message.lock().unwrap() =
116 Some(String::from("Error in parsing launch command"));
117 return (false, app);
118 }
119 };
120
121 run_command(command, app.message.clone());
122 }
123 1 => {
124 let command =
125 match app.config.commands.audio_player.clone().as_command_vec(
126 EnvVar {
127 url: Some(match videoinfo.mode {
128 Mode::Youtube => {
129 format!(
130 "https://youtu.be/{}",
131 videoinfo.video.video_id
132 )
133 }
134 Mode::Invidious => {
135 format!(
136 "{}/embed/{}",
137 app.client.server, videoinfo.video.video_id
138 )
139 }
140 }),
141 ..Default::default()
142 },
143 &app.config,
144 ) {
145 Ok(command) => command,
146 Err(_) => {
147 *app.message.lock().unwrap() =
148 Some(String::from("Error in parsing launch command"));
149 return (false, app);
150 }
151 };
152
153 run_command(command, app.message.clone());
154 }
155 2 => {
156 let command =
157 match app.config.commands.video_downloader.clone().as_command_vec(
158 EnvVar {
159 url: Some(match videoinfo.mode {
160 Mode::Youtube => {
161 format!(
162 "https://youtu.be/{}",
163 videoinfo.video.video_id
164 )
165 }
166 Mode::Invidious => {
167 format!(
168 "{}/embed/{}",
169 app.client.server, videoinfo.video.video_id
170 )
171 }
172 }),
173 ..Default::default()
174 },
175 &app.config,
176 ) {
177 Ok(command) => command,
178 Err(_) => {
179 *app.message.lock().unwrap() =
180 Some(String::from("Error in parsing launch command"));
181 return (false, app);
182 }
183 };
184
185 run_command(command, app.message.clone());
186 }
187 3 => {
188 let command =
189 match app.config.commands.audio_downloader.clone().as_command_vec(
190 EnvVar {
191 url: Some(match videoinfo.mode {
192 Mode::Youtube => {
193 format!(
194 "https://youtu.be/{}",
195 videoinfo.video.video_id
196 )
197 }
198 Mode::Invidious => {
199 format!(
200 "{}/embed/{}",
201 app.client.server, videoinfo.video.video_id
202 )
203 }
204 }),
205 ..Default::default()
206 },
207 &app.config,
208 ) {
209 Ok(command) => command,
210 Err(_) => {
211 *app.message.lock().unwrap() =
212 Some(String::from("Error in parsing launch command"));
213 return (false, app);
214 }
215 };
216
217 run_command(command, app.message.clone());
218 }
219 4 => {
220 let mut dir = home::home_dir().unwrap();
221
222 dir.push(".cache");
223 dir.push("youtube-tui");
224 dir.push("thumbnails");
225 dir.push(format!("{}.png", videoinfo.video.video_id));
226
227 let command =
228 match app.config.commands.image_viewer.clone().as_command_vec(
229 EnvVar {
230 url: Some((*dir.as_path().to_string_lossy()).to_string()),
231 ..Default::default()
232 },
233 &app.config,
234 ) {
235 Ok(command) => command,
236 Err(_) => {
237 *app.message.lock().unwrap() =
238 Some(String::from("Error in parsing launch command"));
239 return (false, app);
240 }
241 };
242
243 run_command(command, app.message.clone());
244 }
245 5 => {
84 ItemInfoItem::Video(videoinfo) => match action {
85 Action::Up => videoinfo.list.up(),
86 Action::Down => videoinfo.list.down(),
87 Action::FirstItem => videoinfo.list.selected = 0,
88 Action::LastItem => videoinfo.list.selected = videoinfo.list.items.len() - 1,
89 Action::Select => {
90 let command = &videoinfo.commands[videoinfo.list.selected];
91
92 match command.command.as_str() {
93 "{toggle_mode}" => videoinfo.mode.toggle(),
94 "{goto_channel}" => {
24695 let state = Channel::default();
24796 let mut history = app.history.clone();
24897 history.push(app.into());
@@ -261,259 +110,61 @@ impl ItemTrait for ItemInfoItem {
261110 },
262111 );
263112 }
264 6 => {
265 videoinfo.mode.toggle();
266 }
113 _ => {
114 match app.config.commands.0.get(&command.command) {
115 Some(command) => {
116 let mut env = app.config.main.env.clone();
117
118 env.insert(
119 String::from("embed_url"),
120 format!(
121 "{}/embed/{}",
122 match videoinfo.mode {
123 Mode::Invidious => app.client.server.as_str(),
124 Mode::Youtube => "https://youtube.com",
125 },
126 videoinfo.video.video_id
127 ),
128 );
267129
268 _ => {}
269 }
130 match command.run_command(&env) {
131 Some(e) => {
132 *app.message.lock().unwrap() =
133 Some(format!("Unknown variable `{}`", e))
134 }
135 None => {
136 *app.message.lock().unwrap() =
137 Some(command.message.clone())
138 }
139 }
140 }
141 None => {
142 *app.message.lock().unwrap() =
143 Some(format!("Unkown command `{}`", &command.command));
144 }
145 };
146 }
147 };
270148 }
271149 _ => {}
272150 },
273151
274152 ItemInfoItem::PlayList(playlistinfo) => match playlistinfo.display_view {
275 PlayListDisplayView::PlayListView => match key {
276 KeyCode::Up => playlistinfo.playlist_view_list.up(),
277 KeyCode::Down => playlistinfo.playlist_view_list.down(),
278 KeyCode::PageUp => playlistinfo.playlist_view_list.selected = 0,
279 KeyCode::PageDown => {
153 PlayListDisplayView::PlayListView => match action {
154 Action::Up => playlistinfo.playlist_view_list.up(),
155 Action::Down => playlistinfo.playlist_view_list.down(),
156 Action::FirstItem => playlistinfo.playlist_view_list.selected = 0,
157 Action::LastItem => {
280158 playlistinfo.playlist_view_list.selected =
281159 playlistinfo.playlist_view_list.items.len() - 1
282160 }
283 KeyCode::Enter => {
284 if playlistinfo.playlist_view_list.selected > 0
285 && playlistinfo.playlist_view_list.selected < 7
286 {
287 *app.message.lock().unwrap() =
288 Some(String::from("Launched application"));
289 }
161 Action::Select => {
162 let command =
163 &playlistinfo.commands[playlistinfo.playlist_view_list.selected];
290164
291 match playlistinfo.playlist_view_list.selected {
292 0 => {
293 playlistinfo.display_view = playlistinfo.display_view.toggle();
294 }
295
296 1 => {
297 let command = match app
298 .config
299 .commands
300 .playlist_video_all
301 .clone()
302 .as_command_vec(
303 EnvVar {
304 url: Some(match playlistinfo.mode {
305 Mode::Youtube => {
306 format!(
307 "https://www.youtube.com/playlist?list={}",
308 playlistinfo.playlist.playlist_id
309 )
310 }
311 Mode::Invidious => {
312 format!(
313 "{}/playlist?list={}",
314 app.client.server,
315 playlistinfo.playlist.playlist_id
316 )
317 }
318 }),
319 ..Default::default()
320 },
321 &app.config,
322 ) {
323 Ok(command) => command,
324 Err(_) => {
325 *app.message.lock().unwrap() =
326 Some(String::from("Error in parsing launch command"));
327 return (false, app);
328 }
329 };
330
331 run_command(command, app.message.clone());
332 }
333
334 2 => {
335 let command = match app
336 .config
337 .commands
338 .playlist_audio_all
339 .clone()
340 .as_command_vec(
341 EnvVar {
342 url: Some(match playlistinfo.mode {
343 Mode::Youtube => {
344 format!(
345 "https://www.youtube.com/playlist?list={}",
346 playlistinfo.playlist.playlist_id
347 )
348 }
349 Mode::Invidious => {
350 format!(
351 "{}/playlist?list={}",
352 app.client.server,
353 playlistinfo.playlist.playlist_id
354 )
355 }
356 }),
357 ..Default::default()
358 },
359 &app.config,
360 ) {
361 Ok(command) => command,
362 Err(_) => {
363 *app.message.lock().unwrap() =
364 Some(String::from("Error in parsing launch command"));
365 return (false, app);
366 }
367 };
368
369 run_command(command, app.message.clone());
370 }
371
372 3 => {
373 let command = match app
374 .config
375 .commands
376 .playlist_shuffle_audio_all
377 .clone()
378 .as_command_vec(
379 EnvVar {
380 url: Some(match playlistinfo.mode {
381 Mode::Youtube => {
382 format!(
383 "https://www.youtube.com/playlist?list={}",
384 playlistinfo.playlist.playlist_id
385 )
386 }
387 Mode::Invidious => {
388 format!(
389 "{}/playlist?list={}",
390 app.client.server,
391 playlistinfo.playlist.playlist_id
392 )
393 }
394 }),
395 ..Default::default()
396 },
397 &app.config,
398 ) {
399 Ok(command) => command,
400 Err(_) => {
401 *app.message.lock().unwrap() =
402 Some(String::from("Error in parsing launch command"));
403 return (false, app);
404 }
405 };
406
407 run_command(command, app.message.clone());
408 }
409
410 4 => {
411 let command = match app
412 .config
413 .commands
414 .download_all_video
415 .clone()
416 .as_command_vec(
417 EnvVar {
418 url: Some(match playlistinfo.mode {
419 Mode::Youtube => {
420 format!(
421 "https://www.youtube.com/playlist?list={}",
422 playlistinfo.playlist.playlist_id
423 )
424 }
425 Mode::Invidious => {
426 format!(
427 "{}/playlist?list={}",
428 app.client.server,
429 playlistinfo.playlist.playlist_id
430 )
431 }
432 }),
433 ..Default::default()
434 },
435 &app.config,
436 ) {
437 Ok(command) => command,
438 Err(_) => {
439 *app.message.lock().unwrap() =
440 Some(String::from("Error in parsing launch command"));
441 return (false, app);
442 }
443 };
444
445 run_command(command, app.message.clone());
446 }
447
448 5 => {
449 let command = match app
450 .config
451 .commands
452 .download_all_audio
453 .clone()
454 .as_command_vec(
455 EnvVar {
456 url: Some(match playlistinfo.mode {
457 Mode::Youtube => {
458 format!(
459 "https://www.youtube.com/playlist?list={}",
460 playlistinfo.playlist.playlist_id
461 )
462 }
463 Mode::Invidious => {
464 format!(
465 "{}/playlist?list={}",
466 app.client.server,
467 playlistinfo.playlist.playlist_id
468 )
469 }
470 }),
471 ..Default::default()
472 },
473 &app.config,
474 ) {
475 Ok(command) => command,
476 Err(_) => {
477 *app.message.lock().unwrap() =
478 Some(String::from("Error in parsing launch command"));
479 return (false, app);
480 }
481 };
482
483 run_command(command, app.message.clone());
484 }
485
486 6 => {
487 let mut dir = home::home_dir().unwrap();
488
489 dir.push(".cache");
490 dir.push("youtube-tui");
491 dir.push("thumbnails");
492 dir.push(format!("{}.png", playlistinfo.playlist.playlist_id));
493
494 let command =
495 match app.config.commands.image_viewer.clone().as_command_vec(
496 EnvVar {
497 url: Some(
498 (*dir.as_path().to_string_lossy()).to_string(),
499 ),
500 ..Default::default()
501 },
502 &app.config,
503 ) {
504 Ok(command) => command,
505 Err(_) => {
506 *app.message.lock().unwrap() = Some(String::from(
507 "Error in parsing launch command",
508 ));
509 return (false, app);
510 }
511 };
512
513 run_command(command, app.message.clone());
514 }
515
516 7 => {
165 match command.command.as_str() {
166 "{toggle_mode}" => playlistinfo.mode.toggle(),
167 "{goto_channel}" => {
517168 let state = Channel::default();
518169 let mut history = app.history.clone();
519170 history.push(app.into());
@@ -524,35 +175,66 @@ impl ItemTrait for ItemInfoItem {
524175 history,
525176 page: Page::Channel(
526177 ChannelPage::Home,
527 playlistinfo.playlist.author_id.clone(),
178 playlistinfo.playlist.playlist_id.clone(),
528179 ),
529180 selectable: App::selectable(&state),
530181 state,
531 load: true,
532182 ..Default::default()
533183 },
534184 );
535185 }
536186
537 8 => {
538 playlistinfo.mode.toggle();
187 "{switch_view}" => {
188 playlistinfo.display_view = playlistinfo.display_view.toggle()
539189 }
190 _ => {
191 match app.config.commands.0.get(&command.command) {
192 Some(command) => {
193 let mut env = app.config.main.env.clone();
194
195 env.insert(
196 String::from("embed_url"),
197 format!(
198 "{}/playlist?list={}",
199 match playlistinfo.mode {
200 Mode::Invidious => app.client.server.as_str(),
201 Mode::Youtube => "https://youtube.com",
202 },
203 playlistinfo.playlist.playlist_id
204 ),
205 );
540206
541 _ => {}
542 }
207 match command.run_command(&env) {
208 Some(e) => {
209 *app.message.lock().unwrap() =
210 Some(format!("Unknown variable `{}`", e))
211 }
212 None => {
213 *app.message.lock().unwrap() =
214 Some(command.message.clone())
215 }
216 }
217 }
218 None => {
219 *app.message.lock().unwrap() =
220 Some(format!("Unkown command `{}`", &command.command));
221 }
222 };
223 }
224 };
543225 }
544226
545227 _ => {}
546228 },
547 PlayListDisplayView::VideoList => match key {
548 KeyCode::Up => playlistinfo.video_view_list.up(),
549 KeyCode::Down => playlistinfo.video_view_list.down(),
550 KeyCode::PageUp => playlistinfo.video_view_list.selected = 0,
551 KeyCode::PageDown => {
229 PlayListDisplayView::VideoList => match action {
230 Action::Up => playlistinfo.video_view_list.up(),
231 Action::Down => playlistinfo.video_view_list.down(),
232 Action::FirstItem => playlistinfo.video_view_list.selected = 0,
233 Action::LastItem => {
552234 playlistinfo.video_view_list.selected =
553235 playlistinfo.video_view_list.items.len() - 1
554236 }
555 KeyCode::Enter => match playlistinfo.video_view_list.selected {
237 Action::Select => match playlistinfo.video_view_list.selected {
556238 0 => {
557239 playlistinfo.display_view = playlistinfo.display_view.toggle();
558240 }
@@ -603,20 +285,20 @@ impl ItemTrait for ItemInfoItem {
603285 video.video_thumbnail.clone(),
604286 video.video_id.clone(),
605287 )]));
606 list.items(vec![
607 String::from("Watch video"),
608 String::from("Play audio"),
609 String::from("Download video"),
610 String::from("Download audio"),
611 String::from("View thumbnail"),
612 String::from("Visit channel"),
613 String::from("Mode placeholder"),
614 ]);
288 let commands = app
289 .config
290 .page_commands
291 .0
292 .get("item_info:video")
293 .unwrap_or(&Vec::new())
294 .clone();
295 list.items(commands.iter().map(|item| item.label.to_string()).collect());
615296
616297 let iteminfo = VideoItemInfo {
617298 video,
618299 list,
619300 mode: Mode::Youtube,
301 commands,
620302 };
621303
622304 watch_history.push(
@@ -645,17 +327,15 @@ impl ItemTrait for ItemInfoItem {
645327 .items
646328 .extend(playlist.videos.iter().map(|v| v.title.clone()));
647329
648 playlist_text_list.items(vec![
649 String::from("Switch view"),
650 String::from("Watch all"),
651 String::from("Play all audio"),
652 String::from("Shuffle play all audio"),
653 String::from("Download all video"),
654 String::from("Download all audio"),
655 String::from("View thumbnail"),
656 String::from("Visit channel"),
657 String::from("Mode placeholder"),
658 ]);
330 let commands = app
331 .config
332 .page_commands
333 .0
334 .get("item_info:playlist")
335 .unwrap_or(&Vec::new())
336 .clone();
337 playlist_text_list
338 .items(commands.iter().map(|item| item.label.to_string()).collect());
659339
660340 let iteminfo = PlayListItemInfo {
661341 playlist: playlist,
@@ -663,6 +343,7 @@ impl ItemTrait for ItemInfoItem {
663343 playlist_view_list: playlist_text_list,
664344 mode: Mode::Youtube,
665345 display_view: PlayListDisplayView::PlayListView,
346 commands,
666347 };
667348
668349 watch_history.push(
@@ -682,12 +363,6 @@ impl ItemTrait for ItemInfoItem {
682363 }
683364
684365 fn render_item<B: Backend>(
685 // &mut self,
686 // frame: &mut Frame<B>,
687 // rect: Rect,
688 // selected: bool,
689 // hover: bool,
690 // popup_focus: bool,
691366 &self,
692367 frame: &mut Frame<B>,
693368 rect: Rect,
@@ -701,7 +376,12 @@ impl ItemTrait for ItemInfoItem {
701376 match self {
702377 ItemInfoItem::Video(videoinfo) => {
703378 let mut list = videoinfo.list.clone();
704 list.items[videoinfo.list.items.len() - 1] = format!("Mode: {}", videoinfo.mode);
379
380 list.items.iter_mut().for_each(|item| match item.as_str() {
381 "{mode}" => *item = format!("Mode: {}", videoinfo.mode),
382 _ => {}
383 });
384 // list.items[videoinfo.list.items.len() - 1] = format!("Mode: {}", videoinfo.mode);
705385
706386 let split = HorizontalSplit::default()
707387 .percentages(vec![40, 60])
@@ -771,12 +451,15 @@ impl ItemTrait for ItemInfoItem {
771451 frame.render_widget(list, chunks[1]);
772452 }
773453 PlayListDisplayView::PlayListView => {
774 let mut playlist_view_list = playlistinfo.playlist_view_list.clone();
775 playlist_view_list.items[playlistinfo.playlist_view_list.items.len() - 1] =
776 format!("Mode: {}", playlistinfo.mode);
777
778454 let mut list = playlistinfo.playlist_view_list.clone();
455
456 list.items.iter_mut().for_each(|item| match item.as_str() {
457 "{mode}" => *item = format!("Mode: {}", playlistinfo.mode),
458 _ => {}
459 });
460
779461 list.area(chunks[1]);
462
780463 if selected {
781464 list.selected_style(Style::default().fg(Color::LightRed));
782465 } else {
@@ -859,25 +542,4 @@ impl PageTrait for ItemInfo {
859542 }
860543}
861544
862impl ItemInfoItem {}
863
864fn run_command(args: Vec<String>, message: Arc<Mutex<Option<String>>>) {
865 thread::spawn(move || {
866 let mut args = args.into_iter();
867 let mut command = Command::new(args.next().unwrap());
868 for arg in args {
869 command.arg(arg);
870 }
871
872 let res = command.spawn();
873 if let Err(e) = res {
874 *message.lock().unwrap() = Some(
875 e.to_string()
876 .lines()
877 .next()
878 .unwrap_or("An error occured")
879 .to_string(),
880 );
881 }
882 });
883}
545impl ItemInfoItem {}
\ No newline at end of file
src/app/pages/main_menu.rs +45 −38
@@ -3,6 +3,7 @@ use std::{collections::LinkedList, error::Error, fs};
33use crate::{
44 app::{
55 app::App,
6 config::Action,
67 pages::{global::*, item_info::*},
78 },
89 functions::download_all_thumbnails,
@@ -254,45 +255,51 @@ impl ItemTrait for MainMenuItem {
254255
255256 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
256257 match self {
257 MainMenuItem::VideoList(Some((list, textlist, _))) => match key {
258 KeyCode::Up => textlist.up(),
259 KeyCode::Down => textlist.down(),
260 KeyCode::PageUp => textlist.selected = 0,
261 KeyCode::PageDown => textlist.selected = textlist.items.len() - 1,
262 KeyCode::Enter => {
263 let state = ItemInfo::default();
264 let mut history = app.history.clone();
265 history.push(app.into());
266
267 return (
268 false,
269 App {
270 history,
271 page: Page::ItemDisplay(
272 match list.iter().nth(textlist.selected).unwrap() {
273 ListItem::FullVideo(item) => {
274 DisplayItem::Video(item.video_id.clone())
275 }
276 ListItem::FullPlayList(item) => {
277 DisplayItem::PlayList(item.playlist_id.clone())
278 }
279 ListItem::MiniPlayList(item) => {
280 DisplayItem::PlayList(item.playlist_id.clone())
281 }
282 ListItem::MiniVideo(item) => {
283 DisplayItem::Video(item.video_id.clone())
284 }
285 _ => unreachable!(),
286 },
287 ),
288 selectable: App::selectable(&state),
289 state,
290 ..Default::default()
291 },
292 );
258 MainMenuItem::VideoList(Some((list, textlist, _))) => {
259 let action = match app.config.keybindings.0.get(&key) {
260 Some(action) => action,
261 None => return (false, app),
262 };
263 match action {
264 Action::Up => textlist.up(),
265 Action::Down => textlist.down(),
266 Action::FirstItem => textlist.selected = 0,
267 Action::LastItem => textlist.selected = textlist.items.len() - 1,
268 Action::Select => {
269 let state = ItemInfo::default();
270 let mut history = app.history.clone();
271 history.push(app.into());
272
273 return (
274 false,
275 App {
276 history,
277 page: Page::ItemDisplay(
278 match list.iter().nth(textlist.selected).unwrap() {
279 ListItem::FullVideo(item) => {
280 DisplayItem::Video(item.video_id.clone())
281 }
282 ListItem::FullPlayList(item) => {
283 DisplayItem::PlayList(item.playlist_id.clone())
284 }
285 ListItem::MiniPlayList(item) => {
286 DisplayItem::PlayList(item.playlist_id.clone())
287 }
288 ListItem::MiniVideo(item) => {
289 DisplayItem::Video(item.video_id.clone())
290 }
291 _ => unreachable!(),
292 },
293 ),
294 selectable: App::selectable(&state),
295 state,
296 ..Default::default()
297 },
298 );
299 }
300 _ => {}
293301 }
294 _ => {}
295 },
302 }
296303 _ => {}
297304 }
298305
src/app/pages/search.rs +12 −7
@@ -10,7 +10,7 @@ use tui::{
1010};
1111
1212use crate::{
13 app::app::App,
13 app::{app::App, config::Action},
1414 functions::download_all_thumbnails,
1515 structs::{
1616 Item, ListItem, MiniChannel, MiniPlayList, MiniVideo, Page, Row, RowItem, WatchHistory,
@@ -44,13 +44,18 @@ impl ItemTrait for SearchItem {
4444 }
4545
4646 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
47 let action = match app.config.keybindings.0.get(&key) {
48 Some(action) => action,
49 None => return (false, app),
50 };
4751 match self {
48 SearchItem::Search { results, text_list } => match key {
49 KeyCode::Up => text_list.up(),
50 KeyCode::Down => text_list.down(),
51 KeyCode::PageUp => text_list.selected = 0,
52 KeyCode::PageDown => text_list.selected = text_list.items.len() - 1,
53 KeyCode::Enter => {
52
53 SearchItem::Search { results, text_list } => match action {
54 Action::Up => text_list.up(),
55 Action::Down => text_list.down(),
56 Action::FirstItem => text_list.selected = 0,
57 Action::LastItem => text_list.selected = text_list.items.len() - 1,
58 Action::Select => {
5459 if let Some(results_unwrapped) = results {
5560 match results_unwrapped.iter().nth(text_list.selected).unwrap() {
5661 ListItem::PageTurner(b) => {
src/main.rs +11 −9
@@ -1,5 +1,5 @@
11use crossterm::{
2 event::{self, DisableMouseCapture, EnableMouseCapture, KeyCode},
2 event::{self, DisableMouseCapture, EnableMouseCapture},
33 execute,
44 terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
55};
@@ -9,9 +9,7 @@ use tui::{
99 Terminal,
1010};
1111use youtube_tui::{
12 app::{
13 app::App,
14 },
12 app::{app::App, config::Action},
1513 structs::{Row, RowItem},
1614};
1715
@@ -94,11 +92,15 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
9492 match event::read()? {
9593 event::Event::Key(key) => {
9694 if app.selected.is_none() {
97 match key.code {
98 KeyCode::Char('q') => {
95 let action = match app.config.keybindings.0.get(&key.code) {
96 Some(action) => *action,
97 None => continue,
98 };
99 match action {
100 Action::Exit => {
99101 return Ok(());
100102 }
101 KeyCode::Backspace => {
103 Action::Back => {
102104 let holder = app.pop();
103105 app = holder.0;
104106 if holder.1 {
@@ -107,11 +109,11 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
107109 app.render = true;
108110 continue;
109111 }
110 KeyCode::End => {
112 Action::ClearHistory => {
111113 app.history = Vec::new();
112114 continue;
113115 }
114 KeyCode::Home => {
116 Action::Home => {
115117 terminal.clear()?;
116118 app.home();
117119 continue;
src/structs/search_settings.rs +18 −10
@@ -1,6 +1,9 @@
11use crossterm::event::KeyCode;
22
3use crate::widgets::text_list::TextList;
3use crate::{
4 app::config::{Action, Config},
5 widgets::text_list::TextList,
6};
47
58#[derive(Debug, Clone)]
69pub struct SearchSettings {
@@ -63,9 +66,14 @@ impl SearchSettings {
6366 vec
6467 }
6568
66 pub fn key_input(&mut self, keycode: KeyCode) {
67 match keycode {
68 KeyCode::Up => {
69 pub fn key_input(&mut self, keycode: KeyCode, config: &Config) {
70 let action = match config.keybindings.0.get(&keycode) {
71 Some(action) => *action,
72 None => return,
73 };
74
75 match action {
76 Action::Up => {
6977 if self.row {
7078 self.text_list.up();
7179 self.update_left()
@@ -94,7 +102,7 @@ impl SearchSettings {
94102 }
95103 }
96104 }
97 KeyCode::Down => {
105 Action::Down => {
98106 if self.row {
99107 self.text_list.down();
100108 self.update_left()
@@ -123,13 +131,13 @@ impl SearchSettings {
123131 }
124132 }
125133 }
126 KeyCode::Left => {
134 Action::Left => {
127135 self.row = true;
128136 }
129 KeyCode::Right => {
137 Action::Right => {
130138 self.row = false;
131139 }
132 KeyCode::Enter => {
140 Action::Select => {
133141 if self.text_list.selected == 4 && !self.row {
134142 *self = Self::default();
135143 self.text_list.selected = 4;
@@ -189,8 +197,8 @@ impl AsUrlString for SearchSettingsSortBy {
189197 match self {
190198 SearchSettingsSortBy::Relevance => String::from("relevance"),
191199 SearchSettingsSortBy::Rating => String::from("rating"),
192 SearchSettingsSortBy::Date => String::from("upload_date"),
193 SearchSettingsSortBy::ViewCount => String::from("view_count"),
200 SearchSettingsSortBy::Date => String::from("date"),
201 SearchSettingsSortBy::ViewCount => String::from("views"),
194202 }
195203 )
196204 }
src/traits/config.rs added +47
@@ -0,0 +1,47 @@
1use serde::{de::DeserializeOwned, Serialize};
2use std::{
3 error::Error,
4 fmt::Debug,
5 fs::{self, rename},
6 io::Write,
7};
8
9pub trait ConfigItem<'a> {
10 type Struct: Serialize + DeserializeOwned + Debug + Clone + Default;
11 const FILE_NAME: &'static str;
12
13 fn load() -> Result<Self::Struct, Box<dyn Error>>
14 where
15 Self: Sized,
16 {
17 let mut config_path = home::home_dir().expect("Cannot get your home directory");
18 let mut config = Self::Struct::default();
19 config_path.push(".config");
20 config_path.push("youtube-tui");
21 config_path.push(Self::FILE_NAME);
22
23 if config_path.exists() {
24 let content = fs::read_to_string(config_path.as_os_str())?;
25 match serde_yaml::from_str(&content) {
26 Ok(config_from_str) => config = config_from_str,
27 Err(_) => {
28 let mut new_path = config_path.clone();
29 new_path.pop();
30 new_path.push(format!("{}.old", Self::FILE_NAME));
31
32 rename(&config_path, &new_path)?;
33 }
34 }
35 }
36
37 let mut file = fs::OpenOptions::new()
38 .write(true)
39 .truncate(true)
40 .create(true)
41 .open(config_path.as_os_str())?;
42
43 write!(file, "{}", serde_yaml::to_string(&config)?)?;
44
45 Ok(config)
46 }
47}
src/traits/mod.rs +3
@@ -3,3 +3,6 @@ pub use item::*;
33
44mod page;
55pub use page::*;
6
7mod config;
8pub use config::*;