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 = [
1716 1716
1717[[package]] 1717[[package]]
1718name = "youtube-tui" 1718name = "youtube-tui"
1719version = "0.3.0" 1719version = "0.4.0"
1720dependencies = [ 1720dependencies = [
1721 "chrono", 1721 "chrono",
1722 "crossterm", 1722 "crossterm",
Cargo.toml +1 −1
@@ -1,6 +1,6 @@
1[package] 1[package]
2name = "youtube-tui" 2name = "youtube-tui"
3version = "0.3.1" 3version = "0.4.0"
4edition = "2021" 4edition = "2021"
5authors = ["Siriusmart <siriusmart@tuta.io>"] 5authors = ["Siriusmart <siriusmart@tuta.io>"]
6description = "An aesthetically pleasing YouTube TUI written in Rust" 6description = "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
14 14
15This program is being actively developed and there will be new features coming up every commit. 15This program is being actively developed and there will be new features coming up every commit.
16 16
17![Screenshot](https://cdn.discordapp.com/attachments/906941311142219816/990684947830419526/Screenshot_20220626_192433.png)
18
17> ### What's new in this commit 19> ### What's new in this commit
18> 20>
19> * Code is being cleaned up but still unreadable 21> * More code cleanup
20> * Haven't touched this project for a week because of exams, so I'm just trying to figure out how stuff works again 22> * Commands to be ran in Item Info page can be changed, items can be add/removed (in `page_commands.yml`)
21> * Just a little save stat before I overhaul the configs and how it's handled 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)
22 25
23## Installation 26## Installation
24 27
@@ -35,6 +38,16 @@ git clone https://github.com/sirusmart/youtube-tui && cd youtube-tui && cargo bu
35 38
36The 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. 39The 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.
37 40
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
38## Usage 51## Usage
39 52
40### To launch 53### To launch
@@ -47,7 +60,7 @@ youtube-tui # or path to the binary
47 60
48|Key|What does it do| 61|Key|What does it do|
49|---|---| 62|---|---|
50|Arrow keys|Move in corresponding direction| 63|Arrow/Vim keys|Move in corresponding direction|
51|Right arrow|Move cursor right 64|Right arrow|Move cursor right
52|Enter|Select/Launch| 65|Enter|Select/Launch|
53|Q|Quit the program| 66|Q|Quit the program|
@@ -56,6 +69,24 @@ youtube-tui # or path to the binary
56> 69>
57> 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. 70> 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.
58 71
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
59## Credits 90## Credits
60 91
61* [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 92* [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
64 95
65 96
66... and of course, credits to myself for not having the ability to read the docs for ytfzf and decided to make my own instead. 97... 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
68 98
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::{
19}; 19};
20 20
21use super::{ 21use super::{
22 config::Config, 22 config::{Action, Config},
23 pages::{channel::Channel, item_info::ItemInfo, search::Search}, 23 pages::{channel::Channel, item_info::ItemInfo, search::Search},
24}; 24};
25 25
@@ -45,13 +45,14 @@ pub struct App {
45 45
46impl Default for App { 46impl Default for App {
47 fn default() -> Self { 47 fn default() -> Self {
48 let config = Config::load().unwrap();
48 let state = MainMenu::default(); 49 let state = MainMenu::default();
49 let selectable = App::selectable(&state); 50 let selectable = App::selectable(&state);
50 Self { 51 Self {
51 page: Page::default(), 52 page: Page::default(),
52 state, 53 state,
53 selectable, 54 selectable,
54 client: Client::new(String::from("https://vid.puffyan.us")), 55 client: Client::new(config.main.server_url.clone()),
55 selected: None, 56 selected: None,
56 hover: None, 57 hover: None,
57 message: Arc::new(Mutex::new(None)), 58 message: Arc::new(Mutex::new(None)),
@@ -59,7 +60,7 @@ impl Default for App {
59 render: true, 60 render: true,
60 popup_focus: false, 61 popup_focus: false,
61 history: Vec::new(), 62 history: Vec::new(),
62 config: Config::load().unwrap(), 63 config,
63 watch_history: WatchHistory::load(), 64 watch_history: WatchHistory::load(),
64 search_settings: SearchSettings::default(), 65 search_settings: SearchSettings::default(),
65 search_text: String::new(), 66 search_text: String::new(),
@@ -94,8 +95,10 @@ impl App {
94 } 95 }
95 96
96 pub fn key_input(mut self, key: KeyCode) -> App { 97 pub fn key_input(mut self, key: KeyCode) -> App {
98 let action = self.config.keybindings.0.get(&key);
99
97 if let Some((x, y)) = self.selected { 100 if let Some((x, y)) = self.selected {
98 if key != KeyCode::Esc { 101 if action != Some(&Action::Deselect) {
99 let mut item = self.state[y].items[x].item.clone(); 102 let mut item = self.state[y].items[x].item.clone();
100 let updated; 103 let updated;
101 (updated, self) = item.key_input(key, self); 104 (updated, self) = item.key_input(key, self);
@@ -107,8 +110,13 @@ impl App {
107 } 110 }
108 } 111 }
109 112
110 match key { 113 let action = match action {
111 KeyCode::Enter => { 114 Some(action) => *action,
115 None => return self,
116 };
117
118 match action {
119 Action::Select => {
112 if self.hover.is_some() && self.selected.is_none() { 120 if self.hover.is_some() && self.selected.is_none() {
113 let (mut x, mut y) = self.hover.unwrap(); 121 let (mut x, mut y) = self.hover.unwrap();
114 (x, y) = self.selectable[y][x]; 122 (x, y) = self.selectable[y][x];
@@ -130,7 +138,7 @@ impl App {
130 return self; 138 return self;
131 } 139 }
132 } 140 }
133 KeyCode::Esc => { 141 Action::Deselect => {
134 if self.selected.is_some() { 142 if self.selected.is_some() {
135 self.selected = None; 143 self.selected = None;
136 self.popup_focus = false; 144 self.popup_focus = false;
@@ -142,8 +150,8 @@ impl App {
142 } 150 }
143 151
144 match &mut self.hover { 152 match &mut self.hover {
145 Some((x, y)) => match key { 153 Some((x, y)) => match action {
146 KeyCode::Up => { 154 Action::Up => {
147 if *y > 0 { 155 if *y > 0 {
148 let temp_y = *y - 1; 156 let temp_y = *y - 1;
149 if *x > self.selectable[temp_y].len() { 157 if *x > self.selectable[temp_y].len() {
@@ -158,7 +166,7 @@ impl App {
158 } 166 }
159 } 167 }
160 } 168 }
161 KeyCode::Down => { 169 Action::Down => {
162 if *y < self.selectable.len() - 1 { 170 if *y < self.selectable.len() - 1 {
163 *y += 1; 171 *y += 1;
164 if *x > self.selectable[*y].len() - 1 { 172 if *x > self.selectable[*y].len() - 1 {
@@ -167,13 +175,13 @@ impl App {
167 } 175 }
168 } 176 }
169 177
170 KeyCode::Left => { 178 Action::Left => {
171 if *x > 0 { 179 if *x > 0 {
172 *x -= 1; 180 *x -= 1;
173 } 181 }
174 } 182 }
175 183
176 KeyCode::Right => { 184 Action::Right => {
177 if *x < self.selectable[*y].len() - 1 { 185 if *x < self.selectable[*y].len() - 1 {
178 *x += 1; 186 *x += 1;
179 } 187 }
@@ -181,17 +189,17 @@ impl App {
181 189
182 _ => {} 190 _ => {}
183 }, 191 },
184 None => match key { 192 None => match action {
185 KeyCode::Up => { 193 Action::Up => {
186 self.hover = Some((0, 0)); 194 self.hover = Some((0, 0));
187 } 195 }
188 KeyCode::Down => { 196 Action::Down => {
189 self.hover = Some((0, self.selectable.len() - 1)); 197 self.hover = Some((0, self.selectable.len() - 1));
190 } 198 }
191 KeyCode::Left => { 199 Action::Left => {
192 self.hover = Some((0, 0)); 200 self.hover = Some((0, 0));
193 } 201 }
194 KeyCode::Right => { 202 Action::Right => {
195 self.hover = Some((0, self.selectable.len() - 1)); 203 self.hover = Some((0, self.selectable.len() - 1));
196 } 204 }
197 _ => {} 205 _ => {}
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
7use serde::{Deserialize, Serialize}; 1use serde::{Deserialize, Serialize};
2use std::{collections::HashMap, thread};
8 3
9use crate::functions::insert_vec; 4use crate::traits::ConfigItem;
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}
42 5
43#[derive(Clone, Debug, Serialize, Deserialize)] 6#[derive(Serialize, Deserialize, Clone, Debug)]
44pub struct CommandConfig { 7pub struct Command {
45 pub command: String,
46 pub open_in_console: bool,
47 pub args: Vec<String>, 8 pub args: Vec<String>,
9 pub message: String,
48} 10}
49 11
50impl CommandConfig { 12#[derive(Serialize, Deserialize, Clone, Debug)]
51 pub fn as_vec(&self) -> Vec<String> { 13pub struct CommandsConfig(pub HashMap<String, Command>);
52 let mut args = self.args.clone(); 14
53 args.insert(0, self.command.clone()); 15impl Command {
54 args 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)
55 } 30 }
56 31
57 pub fn as_command_vec(self, env: EnvVar, config: &Config) -> Result<Vec<String>, ()> { 32 pub fn run_command(&self, variables: &HashMap<String, String>) -> Option<String> {
58 let mut out; 33 let mut args = match self.as_vec(variables) {
59 if self.open_in_console { 34 Ok(args) => args,
60 out = config.commands.terminal.as_vec(); 35 Err(s) => return Some(s),
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();
72 } 36 }
73 37 .into_iter();
74 for x in out.iter_mut() { 38 thread::spawn(move || {
75 match x.as_str() { 39 let mut command = std::process::Command::new(args.next().unwrap());
76 "{url}" => { 40 for arg in args {
77 if let Some(url) = &env.url { 41 command.arg(arg);
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 _ => {}
93 } 42 }
94 }
95 43
96 Ok(out) 44 let _ = command.output();
45 });
46
47 None
97 } 48 }
98} 49}
99 50
100impl Default for CommandsConfig { 51impl Default for CommandsConfig {
101 fn default() -> Self { 52 fn default() -> Self {
102 Self { 53 let mut out = Self::blank();
103 video_player: CommandConfig { 54
104 command: String::from("mpv"), 55 out.insert(
105 open_in_console: false, 56 "video_player",
106 args: vec![String::from("--no-terminal"), String::from("{url}")], 57 vec!["mpv", "{embed_url}", "--no-terminal"],
107 }, 58 "Launched mpv",
108 audio_player: CommandConfig { 59 );
109 command: String::from("mpv"), 60 out.insert(
110 open_in_console: true, 61 "audio_player",
111 args: vec![String::from("--no-video"), String::from("{url}")], 62 vec!["konsole", "-e", "mpv", "{embed_url}", "--no-video"],
112 }, 63 "Opened mpv in new konsole window",
113 image_viewer: CommandConfig { 64 );
114 command: String::from("mpv"), 65 out.insert(
115 open_in_console: false, 66 "audio_playlist_shuffle",
116 args: vec![String::from("{url}"), String::from("--no-terminal")], 67 vec![
117 }, 68 "konsole",
118 video_downloader: CommandConfig { 69 "-e",
119 command: String::from("yt-dlp"), 70 "mpv",
120 open_in_console: true, 71 "{embed_url}",
121 args: vec![ 72 "--no-video",
122 String::from("{url}"), 73 "--shuffle",
123 String::from("-o"), 74 ],
124 String::from("{video_save_location}"), 75 "Opened mpv in new konsole window",
125 ], 76 );
126 }, 77 out.insert(
127 audio_downloader: CommandConfig { 78 "audio_playlist_loop",
128 command: String::from("yt-dlp"), 79 vec![
129 open_in_console: true, 80 "konsole",
130 args: vec![ 81 "-e",
131 String::from("{url}"), 82 "mpv",
132 String::from("-o"), 83 "{embed_url}",
133 String::from("{audio_save_location}"), 84 "--no-video",
134 String::from("-x"), 85 "--loop-playlist=inf",
135 ], 86 ],
136 }, 87 "Opened mpv in new konsole window",
137 terminal: CommandConfig { 88 );
138 command: String::from("konsole"), 89 out.insert(
139 open_in_console: false, 90 "audio_playlist_shuffle_loop",
140 args: vec![String::from("-e"), String::from("{command}")], 91 vec![
141 }, 92 "konsole",
142 playlist_audio_all: CommandConfig { 93 "-e",
143 command: String::from("mpv"), 94 "mpv",
144 open_in_console: true, 95 "{embed_url}",
145 args: vec![String::from("--no-video"), String::from("{url}")], 96 "--no-video",
146 }, 97 "--loop-playlist=inf",
147 playlist_video_all: CommandConfig { 98 "--shuffle",
148 command: String::from("mpv"), 99 ],
149 open_in_console: false, 100 "Opened mpv in new konsole window",
150 args: vec![String::from("{url}"), String::from("--no-terminal")], 101 );
151 }, 102 out.insert(
152 playlist_shuffle_audio_all: CommandConfig { 103 "video_downloader",
153 command: String::from("mpv"), 104 vec![
154 open_in_console: true, 105 "konsole",
155 args: vec![ 106 "-e",
156 String::from("--no-video"), 107 "yt-dlp",
157 String::from("{url}"), 108 "{embed_url}",
158 String::from("--shuffle"), 109 "-o",
159 ], 110 "{download_location}",
160 }, 111 ],
161 download_all_audio: CommandConfig { 112 "Download has started",
162 command: String::from("yt-dlp"), 113 );
163 open_in_console: true, 114
164 args: vec![ 115 out.insert(
165 String::from("{url}"), 116 "audio_downloader",
166 String::from("-o"), 117 vec![
167 String::from("{audio_save_location}"), 118 "konsole",
168 String::from("-x"), 119 "-e",
169 ], 120 "yt-dlp",
170 }, 121 "{embed_url}",
171 download_all_video: CommandConfig { 122 "-o",
172 command: String::from("yt-dlp"), 123 "{download_location}",
173 open_in_console: true, 124 "-x",
174 args: vec![ 125 ],
175 String::from("{url}"), 126 "Download has started",
176 String::from("-o"), 127 );
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 }
211 128
212 out 129 out
213 } 130 }
214} 131}
215 132
216impl CommandsConfig { 133impl CommandsConfig {
217 pub fn load() -> Result<Self, Box<dyn Error>> { 134 fn blank() -> Self {
218 let mut config = home::home_dir().expect("Cannot get your home directory"); 135 Self(HashMap::default())
219 let mut commands = CommandsConfig::default(); 136 }
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 }
229 137
230 let mut file = OpenOptions::new() 138 fn insert(&mut self, label: &str, command: Vec<&str>, msg: &str) {
231 .write(true) 139 self.0.insert(
232 .truncate(true) 140 label.to_string(),
233 .create(true) 141 Command {
234 .open(config.as_os_str())?; 142 args: command
143 .into_iter()
144 .map(|item| item.to_string())
145 .collect::<Vec<_>>(),
146 message: msg.to_string(),
147 },
148 );
149 }
150}
235 151
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}
237 160
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())
239 } 166 }
240} 167}
src/app/config/config.rs +8 −1
@@ -1,11 +1,14 @@
1use std::error::Error; 1use std::error::Error;
2 2
3use super::{commands::CommandsConfig, MainConfig}; 3use super::{commands::CommandsConfig, MainConfig, PageCommandsConfig, KeybindingsConfig};
4use crate::traits::ConfigItem;
4 5
5#[derive(Clone, Debug)] 6#[derive(Clone, Debug)]
6pub struct Config { 7pub struct Config {
7 pub commands: CommandsConfig, 8 pub commands: CommandsConfig,
8 pub main: MainConfig, 9 pub main: MainConfig,
10 pub page_commands: PageCommandsConfig,
11 pub keybindings: KeybindingsConfig,
9} 12}
10 13
11impl Default for Config { 14impl Default for Config {
@@ -13,6 +16,8 @@ impl Default for Config {
13 Self { 16 Self {
14 commands: CommandsConfig::default(), 17 commands: CommandsConfig::default(),
15 main: MainConfig::default(), 18 main: MainConfig::default(),
19 page_commands: PageCommandsConfig::default(),
20 keybindings: KeybindingsConfig::default(),
16 } 21 }
17 } 22 }
18} 23}
@@ -22,6 +27,8 @@ impl Config {
22 Ok(Self { 27 Ok(Self {
23 main: MainConfig::load()?, 28 main: MainConfig::load()?,
24 commands: CommandsConfig::load()?, 29 commands: CommandsConfig::load()?,
30 page_commands: PageCommandsConfig::load()?,
31 keybindings: KeybindingsConfig::load()?.into(),
25 }) 32 })
26 } 33 }
27} 34}
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::{ 1use std::collections::HashMap;
2 error::Error,
3 fs::{self, OpenOptions},
4 io::Write,
5};
6 2
3use crate::traits::ConfigItem;
7use serde::{Deserialize, Serialize}; 4use serde::{Deserialize, Serialize};
8 5
9#[derive(Clone, Debug, Serialize, Deserialize)] 6fn max_watch_history_default() -> usize {
10pub struct MainConfigTransitional { 7 50
11 pub yt_dl: Option<YtDlConfig>,
12 pub max_watch_history: Option<usize>,
13} 8}
14 9
15#[derive(Clone, Debug, Serialize, Deserialize)] 10fn server_url_default() -> String {
16pub struct MainConfig { 11 String::from("https://vid.puffyan.us")
17 pub yt_dl: YtDlConfig,
18 pub max_watch_history: usize,
19} 12}
20 13
21impl Default for MainConfig { 14fn env_default() -> HashMap<String, String> {
22 fn default() -> Self { 15 let mut out = HashMap::default();
23 Self { 16
24 yt_dl: YtDlConfig::default(), 17 out.insert(
25 max_watch_history: 50, 18 String::from("download_location"),
26 } 19 String::from("~/Downloads/%(title)s.%(ext)s"),
27 } 20 );
21
22 out
28} 23}
29 24
30#[derive(Clone, Debug, Serialize, Deserialize)] 25#[derive(Clone, Debug, Serialize, Deserialize)]
31pub struct YtDlConfig { 26pub struct MainConfig {
32 pub video_path: String, 27 #[serde(default = "max_watch_history_default")]
33 pub audio_path: String, 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>,
34} 35}
35 36
36impl Default for YtDlConfig { 37impl Default for MainConfig {
37 fn default() -> Self { 38 fn default() -> Self {
38 Self { 39 Self {
39 video_path: String::from("~/Downloads/%(title)s.%(ext)s"), 40 max_watch_history: max_watch_history_default(),
40 audio_path: String::from("~/Downloads/%(title)s.%(ext)s"), 41 server_url: server_url_default(),
42 env: env_default(),
41 } 43 }
42 } 44 }
43} 45}
44 46
45impl From<MainConfigTransitional> for MainConfig { 47impl ConfigItem<'_> for MainConfig {
46 fn from(config: MainConfigTransitional) -> Self { 48 type Struct = MainConfig;
47 let mut out = MainConfig::default(); 49 const FILE_NAME: &'static str = "main.yml";
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 }
85} 50}
src/app/config/mod.rs +6
@@ -5,3 +5,9 @@ pub use config::*;
5 5
6mod main; 6mod main;
7pub use main::*; 7pub 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::{
10}; 10};
11 11
12use crate::{ 12use crate::{
13 app::app::App, 13 app::{app::App, config::Action},
14 functions::download_all_thumbnails, 14 functions::download_all_thumbnails,
15 structs::{ 15 structs::{
16 FullChannel, Item, ListItem, MiniPlayList, MiniVideo, Page, Row, RowItem, WatchHistory, 16 FullChannel, Item, ListItem, MiniPlayList, MiniVideo, Page, Row, RowItem, WatchHistory,
@@ -294,22 +294,27 @@ impl ItemTrait for ChannelItem {
294 } 294 }
295 295
296 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) { 296 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
297 match self { 302 match self {
298 ChannelItem::InfoDisplay(displayitem) => match displayitem { 303 ChannelItem::InfoDisplay(displayitem) => match displayitem {
299 ChannelDisplayItem::Videos(videos, textlist) => match key { 304 ChannelDisplayItem::Videos(videos, textlist) => match action {
300 KeyCode::Up => { 305 Action::Up => {
301 textlist.up(); 306 textlist.up();
302 } 307 }
303 KeyCode::Down => { 308 Action::Down => {
304 textlist.down(); 309 textlist.down();
305 } 310 }
306 KeyCode::PageUp => { 311 Action::FirstItem => {
307 textlist.selected = 0; 312 textlist.selected = 0;
308 } 313 }
309 KeyCode::PageDown => { 314 Action::LastItem => {
310 textlist.selected = textlist.items.len() - 1; 315 textlist.selected = textlist.items.len() - 1;
311 } 316 }
312 KeyCode::Enter => { 317 Action::Select => {
313 let state = ItemInfo::default(); 318 let state = ItemInfo::default();
314 let mut history = app.history.clone(); 319 let mut history = app.history.clone();
315 history.push(app.into()); 320 history.push(app.into());
@@ -330,20 +335,20 @@ impl ItemTrait for ChannelItem {
330 _ => {} 335 _ => {}
331 }, 336 },
332 337
333 ChannelDisplayItem::Playlists(playlists, textlist) => match key { 338 ChannelDisplayItem::Playlists(playlists, textlist) => match action {
334 KeyCode::Up => { 339 Action::Up => {
335 textlist.up(); 340 textlist.up();
336 } 341 }
337 KeyCode::Down => { 342 Action::Down => {
338 textlist.down(); 343 textlist.down();
339 } 344 }
340 KeyCode::PageUp => { 345 Action::FirstItem => {
341 textlist.selected = 0; 346 textlist.selected = 0;
342 } 347 }
343 KeyCode::PageDown => { 348 Action::LastItem => {
344 textlist.selected = textlist.items.len() - 1; 349 textlist.selected = textlist.items.len() - 1;
345 } 350 }
346 KeyCode::Enter => { 351 Action::Select => {
347 let state = ItemInfo::default(); 352 let state = ItemInfo::default();
348 let mut history = app.history.clone(); 353 let mut history = app.history.clone();
349 history.push(app.into()); 354 history.push(app.into());
src/app/pages/global.rs +2 −11
@@ -26,7 +26,7 @@ pub enum GlobalItem {
26 MessageBar, 26 MessageBar,
27} 27}
28 28
29#[derive(Debug, Clone, Copy)] 29#[derive(Debug, Clone, Copy, PartialEq)]
30pub enum Mode { 30pub enum Mode {
31 Youtube, 31 Youtube,
32 Invidious, 32 Invidious,
@@ -109,7 +109,7 @@ impl ItemTrait for GlobalItem {
109 _ => {} 109 _ => {}
110 }, 110 },
111 GlobalItem::SearchSettings => { 111 GlobalItem::SearchSettings => {
112 app.search_settings.key_input(key); 112 app.search_settings.key_input(key, &app.config);
113 } 113 }
114 _ => {} 114 _ => {}
115 } 115 }
@@ -118,15 +118,6 @@ impl ItemTrait for GlobalItem {
118 } 118 }
119 119
120 fn render_item<B: Backend>( 120 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,
130 &self, 121 &self,
131 frame: &mut Frame<B>, 122 frame: &mut Frame<B>,
132 rect: Rect, 123 rect: Rect,
src/app/pages/item_info.rs +144 −482
@@ -1,13 +1,14 @@
1use std::{ 1use std::{
2 collections::LinkedList, 2 collections::LinkedList,
3 error::Error, 3 error::Error,
4 process::Command,
5 sync::{Arc, Mutex},
6 thread,
7}; 4};
8 5
9use crate::{ 6use crate::{
10 app::{app::App, config::EnvVar, pages::global::*}, 7 app::{
8 app::App,
9 config::{Action, PageCommand},
10 pages::{channel::*, global::*},
11 },
11 functions::download_all_thumbnails, 12 functions::download_all_thumbnails,
12 structs::{FullPlayList, FullVideo, Item, ListItem, Page, Row, RowItem, WatchHistory}, 13 structs::{FullPlayList, FullVideo, Item, ListItem, Page, Row, RowItem, WatchHistory},
13 traits::{ItemTrait, PageTrait}, 14 traits::{ItemTrait, PageTrait},
@@ -21,10 +22,7 @@ use tui::{
21 Frame, 22 Frame,
22}; 23};
23 24
24use super::{ 25use super::global::GlobalItem;
25 channel::{Channel, ChannelPage},
26 global::GlobalItem,
27};
28 26
29#[derive(Debug, Clone)] 27#[derive(Debug, Clone)]
30pub enum ItemInfoItem { 28pub enum ItemInfoItem {
@@ -38,6 +36,7 @@ pub struct VideoItemInfo {
38 video: FullVideo, 36 video: FullVideo,
39 list: TextList, 37 list: TextList,
40 mode: Mode, 38 mode: Mode,
39 commands: Vec<PageCommand>,
41} 40}
42 41
43#[derive(Debug, Clone)] 42#[derive(Debug, Clone)]
@@ -47,6 +46,7 @@ pub struct PlayListItemInfo {
47 playlist_view_list: TextList, 46 playlist_view_list: TextList,
48 display_view: PlayListDisplayView, 47 display_view: PlayListDisplayView,
49 mode: Mode, 48 mode: Mode,
49 commands: Vec<PageCommand>,
50} 50}
51 51
52#[derive(Debug, Clone, Copy)] 52#[derive(Debug, Clone, Copy)]
@@ -76,173 +76,22 @@ impl ItemTrait for ItemInfoItem {
76 } 76 }
77 77
78 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) { 78 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 };
79 match self { 83 match self {
80 ItemInfoItem::Video(videoinfo) => match key { 84 ItemInfoItem::Video(videoinfo) => match action {
81 KeyCode::Up => videoinfo.list.up(), 85 Action::Up => videoinfo.list.up(),
82 KeyCode::Down => videoinfo.list.down(), 86 Action::Down => videoinfo.list.down(),
83 KeyCode::PageUp => videoinfo.list.selected = 0, 87 Action::FirstItem => videoinfo.list.selected = 0,
84 KeyCode::PageDown => videoinfo.list.selected = videoinfo.list.items.len() - 1, 88 Action::LastItem => videoinfo.list.selected = videoinfo.list.items.len() - 1,
85 KeyCode::Enter => { 89 Action::Select => {
86 if videoinfo.list.selected < 5 { 90 let command = &videoinfo.commands[videoinfo.list.selected];
87 *app.message.lock().unwrap() = Some(String::from("Launched application")); 91
88 } 92 match command.command.as_str() {
89 93 "{toggle_mode}" => videoinfo.mode.toggle(),
90 match videoinfo.list.selected { 94 "{goto_channel}" => {
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 => {
246 let state = Channel::default(); 95 let state = Channel::default();
247 let mut history = app.history.clone(); 96 let mut history = app.history.clone();
248 history.push(app.into()); 97 history.push(app.into());
@@ -261,259 +110,61 @@ impl ItemTrait for ItemInfoItem {
261 }, 110 },
262 ); 111 );
263 } 112 }
264 6 => { 113 _ => {
265 videoinfo.mode.toggle(); 114 match app.config.commands.0.get(&command.command) {
266 } 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 );
267 129
268 _ => {} 130 match command.run_command(&env) {
269 } 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 };
270 } 148 }
271 _ => {} 149 _ => {}
272 }, 150 },
273 151
274 ItemInfoItem::PlayList(playlistinfo) => match playlistinfo.display_view { 152 ItemInfoItem::PlayList(playlistinfo) => match playlistinfo.display_view {
275 PlayListDisplayView::PlayListView => match key { 153 PlayListDisplayView::PlayListView => match action {
276 KeyCode::Up => playlistinfo.playlist_view_list.up(), 154 Action::Up => playlistinfo.playlist_view_list.up(),
277 KeyCode::Down => playlistinfo.playlist_view_list.down(), 155 Action::Down => playlistinfo.playlist_view_list.down(),
278 KeyCode::PageUp => playlistinfo.playlist_view_list.selected = 0, 156 Action::FirstItem => playlistinfo.playlist_view_list.selected = 0,
279 KeyCode::PageDown => { 157 Action::LastItem => {
280 playlistinfo.playlist_view_list.selected = 158 playlistinfo.playlist_view_list.selected =
281 playlistinfo.playlist_view_list.items.len() - 1 159 playlistinfo.playlist_view_list.items.len() - 1
282 } 160 }
283 KeyCode::Enter => { 161 Action::Select => {
284 if playlistinfo.playlist_view_list.selected > 0 162 let command =
285 && playlistinfo.playlist_view_list.selected < 7 163 &playlistinfo.commands[playlistinfo.playlist_view_list.selected];
286 {
287 *app.message.lock().unwrap() =
288 Some(String::from("Launched application"));
289 }
290 164
291 match playlistinfo.playlist_view_list.selected { 165 match command.command.as_str() {
292 0 => { 166 "{toggle_mode}" => playlistinfo.mode.toggle(),
293 playlistinfo.display_view = playlistinfo.display_view.toggle(); 167 "{goto_channel}" => {
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 => {
517 let state = Channel::default(); 168 let state = Channel::default();
518 let mut history = app.history.clone(); 169 let mut history = app.history.clone();
519 history.push(app.into()); 170 history.push(app.into());
@@ -524,35 +175,66 @@ impl ItemTrait for ItemInfoItem {
524 history, 175 history,
525 page: Page::Channel( 176 page: Page::Channel(
526 ChannelPage::Home, 177 ChannelPage::Home,
527 playlistinfo.playlist.author_id.clone(), 178 playlistinfo.playlist.playlist_id.clone(),
528 ), 179 ),
529 selectable: App::selectable(&state), 180 selectable: App::selectable(&state),
530 state, 181 state,
531 load: true,
532 ..Default::default() 182 ..Default::default()
533 }, 183 },
534 ); 184 );
535 } 185 }
536 186
537 8 => { 187 "{switch_view}" => {
538 playlistinfo.mode.toggle(); 188 playlistinfo.display_view = playlistinfo.display_view.toggle()
539 } 189 }
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 );
540 206
541 _ => {} 207 match command.run_command(&env) {
542 } 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 };
543 } 225 }
544 226
545 _ => {} 227 _ => {}
546 }, 228 },
547 PlayListDisplayView::VideoList => match key { 229 PlayListDisplayView::VideoList => match action {
548 KeyCode::Up => playlistinfo.video_view_list.up(), 230 Action::Up => playlistinfo.video_view_list.up(),
549 KeyCode::Down => playlistinfo.video_view_list.down(), 231 Action::Down => playlistinfo.video_view_list.down(),
550 KeyCode::PageUp => playlistinfo.video_view_list.selected = 0, 232 Action::FirstItem => playlistinfo.video_view_list.selected = 0,
551 KeyCode::PageDown => { 233 Action::LastItem => {
552 playlistinfo.video_view_list.selected = 234 playlistinfo.video_view_list.selected =
553 playlistinfo.video_view_list.items.len() - 1 235 playlistinfo.video_view_list.items.len() - 1
554 } 236 }
555 KeyCode::Enter => match playlistinfo.video_view_list.selected { 237 Action::Select => match playlistinfo.video_view_list.selected {
556 0 => { 238 0 => {
557 playlistinfo.display_view = playlistinfo.display_view.toggle(); 239 playlistinfo.display_view = playlistinfo.display_view.toggle();
558 } 240 }
@@ -603,20 +285,20 @@ impl ItemTrait for ItemInfoItem {
603 video.video_thumbnail.clone(), 285 video.video_thumbnail.clone(),
604 video.video_id.clone(), 286 video.video_id.clone(),
605 )])); 287 )]));
606 list.items(vec![ 288 let commands = app
607 String::from("Watch video"), 289 .config
608 String::from("Play audio"), 290 .page_commands
609 String::from("Download video"), 291 .0
610 String::from("Download audio"), 292 .get("item_info:video")
611 String::from("View thumbnail"), 293 .unwrap_or(&Vec::new())
612 String::from("Visit channel"), 294 .clone();
613 String::from("Mode placeholder"), 295 list.items(commands.iter().map(|item| item.label.to_string()).collect());
614 ]);
615 296
616 let iteminfo = VideoItemInfo { 297 let iteminfo = VideoItemInfo {
617 video, 298 video,
618 list, 299 list,
619 mode: Mode::Youtube, 300 mode: Mode::Youtube,
301 commands,
620 }; 302 };
621 303
622 watch_history.push( 304 watch_history.push(
@@ -645,17 +327,15 @@ impl ItemTrait for ItemInfoItem {
645 .items 327 .items
646 .extend(playlist.videos.iter().map(|v| v.title.clone())); 328 .extend(playlist.videos.iter().map(|v| v.title.clone()));
647 329
648 playlist_text_list.items(vec![ 330 let commands = app
649 String::from("Switch view"), 331 .config
650 String::from("Watch all"), 332 .page_commands
651 String::from("Play all audio"), 333 .0
652 String::from("Shuffle play all audio"), 334 .get("item_info:playlist")
653 String::from("Download all video"), 335 .unwrap_or(&Vec::new())
654 String::from("Download all audio"), 336 .clone();
655 String::from("View thumbnail"), 337 playlist_text_list
656 String::from("Visit channel"), 338 .items(commands.iter().map(|item| item.label.to_string()).collect());
657 String::from("Mode placeholder"),
658 ]);
659 339
660 let iteminfo = PlayListItemInfo { 340 let iteminfo = PlayListItemInfo {
661 playlist: playlist, 341 playlist: playlist,
@@ -663,6 +343,7 @@ impl ItemTrait for ItemInfoItem {
663 playlist_view_list: playlist_text_list, 343 playlist_view_list: playlist_text_list,
664 mode: Mode::Youtube, 344 mode: Mode::Youtube,
665 display_view: PlayListDisplayView::PlayListView, 345 display_view: PlayListDisplayView::PlayListView,
346 commands,
666 }; 347 };
667 348
668 watch_history.push( 349 watch_history.push(
@@ -682,12 +363,6 @@ impl ItemTrait for ItemInfoItem {
682 } 363 }
683 364
684 fn render_item<B: Backend>( 365 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,
691 &self, 366 &self,
692 frame: &mut Frame<B>, 367 frame: &mut Frame<B>,
693 rect: Rect, 368 rect: Rect,
@@ -701,7 +376,12 @@ impl ItemTrait for ItemInfoItem {
701 match self { 376 match self {
702 ItemInfoItem::Video(videoinfo) => { 377 ItemInfoItem::Video(videoinfo) => {
703 let mut list = videoinfo.list.clone(); 378 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);
705 385
706 let split = HorizontalSplit::default() 386 let split = HorizontalSplit::default()
707 .percentages(vec![40, 60]) 387 .percentages(vec![40, 60])
@@ -771,12 +451,15 @@ impl ItemTrait for ItemInfoItem {
771 frame.render_widget(list, chunks[1]); 451 frame.render_widget(list, chunks[1]);
772 } 452 }
773 PlayListDisplayView::PlayListView => { 453 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
778 let mut list = playlistinfo.playlist_view_list.clone(); 454 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
779 list.area(chunks[1]); 461 list.area(chunks[1]);
462
780 if selected { 463 if selected {
781 list.selected_style(Style::default().fg(Color::LightRed)); 464 list.selected_style(Style::default().fg(Color::LightRed));
782 } else { 465 } else {
@@ -859,25 +542,4 @@ impl PageTrait for ItemInfo {
859 } 542 }
860} 543}
861 544
862impl ItemInfoItem {} 545impl ItemInfoItem {}\ No newline at end of file
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}
src/app/pages/main_menu.rs +45 −38
@@ -3,6 +3,7 @@ use std::{collections::LinkedList, error::Error, fs};
3use crate::{ 3use crate::{
4 app::{ 4 app::{
5 app::App, 5 app::App,
6 config::Action,
6 pages::{global::*, item_info::*}, 7 pages::{global::*, item_info::*},
7 }, 8 },
8 functions::download_all_thumbnails, 9 functions::download_all_thumbnails,
@@ -254,45 +255,51 @@ impl ItemTrait for MainMenuItem {
254 255
255 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) { 256 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
256 match self { 257 match self {
257 MainMenuItem::VideoList(Some((list, textlist, _))) => match key { 258 MainMenuItem::VideoList(Some((list, textlist, _))) => {
258 KeyCode::Up => textlist.up(), 259 let action = match app.config.keybindings.0.get(&key) {
259 KeyCode::Down => textlist.down(), 260 Some(action) => action,
260 KeyCode::PageUp => textlist.selected = 0, 261 None => return (false, app),
261 KeyCode::PageDown => textlist.selected = textlist.items.len() - 1, 262 };
262 KeyCode::Enter => { 263 match action {
263 let state = ItemInfo::default(); 264 Action::Up => textlist.up(),
264 let mut history = app.history.clone(); 265 Action::Down => textlist.down(),
265 history.push(app.into()); 266 Action::FirstItem => textlist.selected = 0,
266 267 Action::LastItem => textlist.selected = textlist.items.len() - 1,
267 return ( 268 Action::Select => {
268 false, 269 let state = ItemInfo::default();
269 App { 270 let mut history = app.history.clone();
270 history, 271 history.push(app.into());
271 page: Page::ItemDisplay( 272
272 match list.iter().nth(textlist.selected).unwrap() { 273 return (
273 ListItem::FullVideo(item) => { 274 false,
274 DisplayItem::Video(item.video_id.clone()) 275 App {
275 } 276 history,
276 ListItem::FullPlayList(item) => { 277 page: Page::ItemDisplay(
277 DisplayItem::PlayList(item.playlist_id.clone()) 278 match list.iter().nth(textlist.selected).unwrap() {
278 } 279 ListItem::FullVideo(item) => {
279 ListItem::MiniPlayList(item) => { 280 DisplayItem::Video(item.video_id.clone())
280 DisplayItem::PlayList(item.playlist_id.clone()) 281 }
281 } 282 ListItem::FullPlayList(item) => {
282 ListItem::MiniVideo(item) => { 283 DisplayItem::PlayList(item.playlist_id.clone())
283 DisplayItem::Video(item.video_id.clone()) 284 }
284 } 285 ListItem::MiniPlayList(item) => {
285 _ => unreachable!(), 286 DisplayItem::PlayList(item.playlist_id.clone())
286 }, 287 }
287 ), 288 ListItem::MiniVideo(item) => {
288 selectable: App::selectable(&state), 289 DisplayItem::Video(item.video_id.clone())
289 state, 290 }
290 ..Default::default() 291 _ => unreachable!(),
291 }, 292 },
292 ); 293 ),
294 selectable: App::selectable(&state),
295 state,
296 ..Default::default()
297 },
298 );
299 }
300 _ => {}
293 } 301 }
294 _ => {} 302 }
295 },
296 _ => {} 303 _ => {}
297 } 304 }
298 305
src/app/pages/search.rs +12 −7
@@ -10,7 +10,7 @@ use tui::{
10}; 10};
11 11
12use crate::{ 12use crate::{
13 app::app::App, 13 app::{app::App, config::Action},
14 functions::download_all_thumbnails, 14 functions::download_all_thumbnails,
15 structs::{ 15 structs::{
16 Item, ListItem, MiniChannel, MiniPlayList, MiniVideo, Page, Row, RowItem, WatchHistory, 16 Item, ListItem, MiniChannel, MiniPlayList, MiniVideo, Page, Row, RowItem, WatchHistory,
@@ -44,13 +44,18 @@ impl ItemTrait for SearchItem {
44 } 44 }
45 45
46 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) { 46 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 };
47 match self { 51 match self {
48 SearchItem::Search { results, text_list } => match key { 52
49 KeyCode::Up => text_list.up(), 53 SearchItem::Search { results, text_list } => match action {
50 KeyCode::Down => text_list.down(), 54 Action::Up => text_list.up(),
51 KeyCode::PageUp => text_list.selected = 0, 55 Action::Down => text_list.down(),
52 KeyCode::PageDown => text_list.selected = text_list.items.len() - 1, 56 Action::FirstItem => text_list.selected = 0,
53 KeyCode::Enter => { 57 Action::LastItem => text_list.selected = text_list.items.len() - 1,
58 Action::Select => {
54 if let Some(results_unwrapped) = results { 59 if let Some(results_unwrapped) = results {
55 match results_unwrapped.iter().nth(text_list.selected).unwrap() { 60 match results_unwrapped.iter().nth(text_list.selected).unwrap() {
56 ListItem::PageTurner(b) => { 61 ListItem::PageTurner(b) => {
src/main.rs +11 −9
@@ -1,5 +1,5 @@
1use crossterm::{ 1use crossterm::{
2 event::{self, DisableMouseCapture, EnableMouseCapture, KeyCode}, 2 event::{self, DisableMouseCapture, EnableMouseCapture},
3 execute, 3 execute,
4 terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, 4 terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
5}; 5};
@@ -9,9 +9,7 @@ use tui::{
9 Terminal, 9 Terminal,
10}; 10};
11use youtube_tui::{ 11use youtube_tui::{
12 app::{ 12 app::{app::App, config::Action},
13 app::App,
14 },
15 structs::{Row, RowItem}, 13 structs::{Row, RowItem},
16}; 14};
17 15
@@ -94,11 +92,15 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
94 match event::read()? { 92 match event::read()? {
95 event::Event::Key(key) => { 93 event::Event::Key(key) => {
96 if app.selected.is_none() { 94 if app.selected.is_none() {
97 match key.code { 95 let action = match app.config.keybindings.0.get(&key.code) {
98 KeyCode::Char('q') => { 96 Some(action) => *action,
97 None => continue,
98 };
99 match action {
100 Action::Exit => {
99 return Ok(()); 101 return Ok(());
100 } 102 }
101 KeyCode::Backspace => { 103 Action::Back => {
102 let holder = app.pop(); 104 let holder = app.pop();
103 app = holder.0; 105 app = holder.0;
104 if holder.1 { 106 if holder.1 {
@@ -107,11 +109,11 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
107 app.render = true; 109 app.render = true;
108 continue; 110 continue;
109 } 111 }
110 KeyCode::End => { 112 Action::ClearHistory => {
111 app.history = Vec::new(); 113 app.history = Vec::new();
112 continue; 114 continue;
113 } 115 }
114 KeyCode::Home => { 116 Action::Home => {
115 terminal.clear()?; 117 terminal.clear()?;
116 app.home(); 118 app.home();
117 continue; 119 continue;
src/structs/search_settings.rs +18 −10
@@ -1,6 +1,9 @@
1use crossterm::event::KeyCode; 1use crossterm::event::KeyCode;
2 2
3use crate::widgets::text_list::TextList; 3use crate::{
4 app::config::{Action, Config},
5 widgets::text_list::TextList,
6};
4 7
5#[derive(Debug, Clone)] 8#[derive(Debug, Clone)]
6pub struct SearchSettings { 9pub struct SearchSettings {
@@ -63,9 +66,14 @@ impl SearchSettings {
63 vec 66 vec
64 } 67 }
65 68
66 pub fn key_input(&mut self, keycode: KeyCode) { 69 pub fn key_input(&mut self, keycode: KeyCode, config: &Config) {
67 match keycode { 70 let action = match config.keybindings.0.get(&keycode) {
68 KeyCode::Up => { 71 Some(action) => *action,
72 None => return,
73 };
74
75 match action {
76 Action::Up => {
69 if self.row { 77 if self.row {
70 self.text_list.up(); 78 self.text_list.up();
71 self.update_left() 79 self.update_left()
@@ -94,7 +102,7 @@ impl SearchSettings {
94 } 102 }
95 } 103 }
96 } 104 }
97 KeyCode::Down => { 105 Action::Down => {
98 if self.row { 106 if self.row {
99 self.text_list.down(); 107 self.text_list.down();
100 self.update_left() 108 self.update_left()
@@ -123,13 +131,13 @@ impl SearchSettings {
123 } 131 }
124 } 132 }
125 } 133 }
126 KeyCode::Left => { 134 Action::Left => {
127 self.row = true; 135 self.row = true;
128 } 136 }
129 KeyCode::Right => { 137 Action::Right => {
130 self.row = false; 138 self.row = false;
131 } 139 }
132 KeyCode::Enter => { 140 Action::Select => {
133 if self.text_list.selected == 4 && !self.row { 141 if self.text_list.selected == 4 && !self.row {
134 *self = Self::default(); 142 *self = Self::default();
135 self.text_list.selected = 4; 143 self.text_list.selected = 4;
@@ -189,8 +197,8 @@ impl AsUrlString for SearchSettingsSortBy {
189 match self { 197 match self {
190 SearchSettingsSortBy::Relevance => String::from("relevance"), 198 SearchSettingsSortBy::Relevance => String::from("relevance"),
191 SearchSettingsSortBy::Rating => String::from("rating"), 199 SearchSettingsSortBy::Rating => String::from("rating"),
192 SearchSettingsSortBy::Date => String::from("upload_date"), 200 SearchSettingsSortBy::Date => String::from("date"),
193 SearchSettingsSortBy::ViewCount => String::from("view_count"), 201 SearchSettingsSortBy::ViewCount => String::from("views"),
194 } 202 }
195 ) 203 )
196 } 204 }
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::*;
3 3
4mod page; 4mod page;
5pub use page::*; 5pub use page::*;
6
7mod config;
8pub use config::*;