Commit 6f8b64c4fa

6f8b64c4fa1b89868a2dbaa1bbd9fda20ecd0768

parent: 2737f15310

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-06-01 10:24 UTC

Playlist support

Layout: unified · split

Cargo.lock +3 −3
@@ -626,9 +626,9 @@ dependencies = [
626 626
627[[package]] 627[[package]]
628name = "invidious" 628name = "invidious"
629version = "0.2.0" 629version = "0.2.1"
630source = "registry+https://github.com/rust-lang/crates.io-index" 630source = "registry+https://github.com/rust-lang/crates.io-index"
631checksum = "89779909e071231edd52fae0a93b5c0a9b3d0d87f83fa0e4f2a958d8c9d66d0a" 631checksum = "b6d4c6a7a9048464b7265d607d7d94469143ae51bc76338a103f7d088c0e5da7"
632dependencies = [ 632dependencies = [
633 "reqwest", 633 "reqwest",
634 "serde", 634 "serde",
@@ -1716,7 +1716,7 @@ dependencies = [
1716 1716
1717[[package]] 1717[[package]]
1718name = "youtube-tui" 1718name = "youtube-tui"
1719version = "0.1.0" 1719version = "0.2.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.1.0" 3version = "0.2.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 +50 −6
@@ -3,20 +3,30 @@
3* This app is only for *\*nix* systems 3* This app is only for *\*nix* systems
4 4
5## Changes made in this commit 5## Changes made in this commit
6* Search support for video (Cannot display channel and playlists yet) 6* Playlist support
7* Adaptive config files (e.g. auto update config files while preserving the original options)
7 8
8## Installation 9## Installation
9Requirements: Git, Cargo and the Rust Compiler 10Requirements: Git, Cargo and the Rust Compiler
10 11
12Executable size: ~12.5MB
13
11```bash 14```bash
15# Install from crates.io (might not be as up-to-date as the one on GitHub)
12cargo install youtube-tui 16cargo install youtube-tui
13``` 17```
14 18
19```bash
20# Install from GitHub with cargo install (The binary will be placed in ~/.cargo/bin, and can be called with `youtube-tui`)
21git clone https://github.com/siriusmart/youtube-tui && cd youtube-tui && cargo install --path . && cd .. && rm -rf youtube-tui
22```
23
15## Features 24## Features
16* View the Trending and Popular tab of YouTube 25* View the Trending and Popular tab of YouTube
17* View your Watch history 26* View your Watch history
18* Download videos and audio 27* Download videos and audio
19* Watch videos and audio 28* Watch videos and audio
29* Video and playlist support
20 30
21## Movement 31## Movement
22* Use the arrow keys to move around the screen 32* Use the arrow keys to move around the screen
@@ -37,7 +47,7 @@ cargo install youtube-tui
37* Config files are stored in `~/.config/youtube-tui` 47* Config files are stored in `~/.config/youtube-tui`
38 48
39## Config files 49## Config files
40The config files are located in `~/.config/youtube-tui`, run the program once to create the config files. 50The config files are located in `~/.config/youtube-tui`, run the program once to create the config files. The following are the default config files:
41 51
42> ### `main.yml` 52> ### `main.yml`
43> ```yaml 53> ```yaml
@@ -92,11 +102,45 @@ The config files are located in `~/.config/youtube-tui`, run the program once to
92> args: 102> args:
93> - "-e" 103> - "-e"
94> - "{command}" 104> - "{command}"
95> 105> playlist_audio_all:
96 106> command: mpv
107> open_in_console: true
108> args:
109> - "--no-video"
110> - "{url}"
111> playlist_video_all:
112> command: mpv
113> open_in_console: false
114> args:
115> - "{url}"
116> - "--no-terminal"
117> playlist_shuffle_audio_all:
118> command: mpv
119> open_in_console: true
120> args:
121> - "--no-video"
122> - "{url}"
123> - "--shuffle"
124> download_all_audio:
125> command: yt-dlp
126> open_in_console: true
127> args:
128> - "{url}"
129> - "-o"
130> - "{audio_save_location}"
131> - "-x"
132> download_all_video:
133> command: yt-dlp
134> open_in_console: true
135> args:
136> - "{url}"
137> - "-o"
138> - "{video_save_location}"
139> ```
97## To Do 140## To Do
98* Search (For all items) 141* Channel support
99* Adaptive config files (auto update when config files when there are new options in the config) 142* Update notice (e.g. when a new version is released on GitHub or crates.io, can be disabled in the config file)
143* Keybind options (e.g. change the keybinds in the config file)
100 144
101## Bugs 145## Bugs
102* If there is a bug please open a GitHub issue thx :)\ No newline at end of file 146* If there is a bug please open a GitHub issue thx :)\ No newline at end of file
src/app/config/commands.rs +118
@@ -1,9 +1,30 @@
1use std::{
2 error::Error,
3 fs::{self, OpenOptions},
4 io::Write,
5};
6
1use serde::{Deserialize, Serialize}; 7use serde::{Deserialize, Serialize};
2 8
3use crate::functions::insert_vec; 9use crate::functions::insert_vec;
4 10
5use super::{Config, EnvVar}; 11use super::{Config, EnvVar};
6 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
7#[derive(Clone, Debug, Serialize, Deserialize)] 28#[derive(Clone, Debug, Serialize, Deserialize)]
8pub struct CommandsConfig { 29pub struct CommandsConfig {
9 pub video_player: CommandConfig, 30 pub video_player: CommandConfig,
@@ -12,6 +33,11 @@ pub struct CommandsConfig {
12 pub video_downloader: CommandConfig, 33 pub video_downloader: CommandConfig,
13 pub audio_downloader: CommandConfig, 34 pub audio_downloader: CommandConfig,
14 pub terminal: 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,
15} 41}
16 42
17#[derive(Clone, Debug, Serialize, Deserialize)] 43#[derive(Clone, Debug, Serialize, Deserialize)]
@@ -113,6 +139,98 @@ impl Default for CommandsConfig {
113 open_in_console: false, 139 open_in_console: false,
114 args: vec![String::from("-e"), String::from("{command}")], 140 args: vec![String::from("-e"), String::from("{command}")],
115 }, 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![String::from("--no-video"), String::from("{url}"), String::from("--shuffle")],
156 },
157 download_all_audio: CommandConfig {
158 command: String::from("yt-dlp"),
159 open_in_console: true,
160 args: vec![
161 String::from("{url}"),
162 String::from("-o"),
163 String::from("{audio_save_location}"),
164 String::from("-x"),
165 ],
166 },
167 download_all_video: CommandConfig {
168 command: String::from("yt-dlp"),
169 open_in_console: true,
170 args: vec![
171 String::from("{url}"),
172 String::from("-o"),
173 String::from("{video_save_location}"),
174 ],
175 },
176 }
177 }
178}
179
180impl From<CommandsConfigTransitional> for CommandsConfig {
181 fn from(original: CommandsConfigTransitional) -> CommandsConfig {
182 let mut out = Self::default();
183
184 if let Some(video_player) = original.video_player {
185 out.video_player = video_player;
186 }
187
188 if let Some(audio_player) = original.audio_player {
189 out.audio_player = audio_player;
190 }
191
192 if let Some(image_viewer) = original.image_viewer {
193 out.image_viewer = image_viewer;
194 }
195
196 if let Some(video_downloader) = original.video_downloader {
197 out.video_downloader = video_downloader;
116 } 198 }
199
200 if let Some(audio_downloader) = original.audio_downloader {
201 out.audio_downloader = audio_downloader;
202 }
203
204 if let Some(terminal) = original.terminal {
205 out.terminal = terminal;
206 }
207
208 out
209 }
210}
211
212impl CommandsConfig {
213 pub fn load() -> Result<Self, Box<dyn Error>> {
214 let mut config = home::home_dir().expect("Cannot get your home directory");
215 let mut commands = CommandsConfig::default();
216 config.push(".config");
217 config.push("youtube-tui");
218 config.push("commands.yml");
219
220 if config.exists() {
221 let content = fs::read_to_string(config.as_os_str())?;
222 let commands_transitional: CommandsConfigTransitional = serde_yaml::from_str(&content)?;
223 commands = commands_transitional.into();
224 }
225
226 let mut file = OpenOptions::new()
227 .write(true)
228 .truncate(true)
229 .create(true)
230 .open(config.as_os_str())?;
231
232 write!(file, "{}", serde_yaml::to_string(&commands)?)?;
233
234 Ok(commands)
117 } 235 }
118} 236}
src/app/config/config.rs +5 −44
@@ -1,8 +1,4 @@
1use std::{ 1use std::error::Error;
2 error::Error,
3 fs::{self, OpenOptions},
4 io::Write,
5};
6 2
7use super::{commands::CommandsConfig, MainConfig}; 3use super::{commands::CommandsConfig, MainConfig};
8 4
@@ -23,45 +19,10 @@ impl Default for Config {
23 19
24impl Config { 20impl Config {
25 pub fn load() -> Result<Self, Box<dyn Error>> { 21 pub fn load() -> Result<Self, Box<dyn Error>> {
26 let mut commands = CommandsConfig::default(); 22 Ok(Self {
27 let mut main = MainConfig::default(); 23 main: MainConfig::load()?,
28 24 commands: CommandsConfig::load()?,
29 let mut config = home::home_dir().expect("Cannot get your home directory"); 25 })
30 config.push(".config");
31 config.push("youtube-tui");
32
33 config.push("commands.yml");
34
35 if config.exists() {
36 let content = fs::read_to_string(config.as_os_str())?;
37 commands = serde_yaml::from_str(&content)?;
38 } else {
39 let mut file = OpenOptions::new()
40 .write(true)
41 .truncate(true)
42 .create(true)
43 .open(config.as_os_str())?;
44
45 write!(file, "{}", serde_yaml::to_string(&commands)?)?;
46 }
47
48 config.pop();
49 config.push("main.yml");
50
51 if config.exists() {
52 let content = fs::read_to_string(config.as_os_str())?;
53 main = serde_yaml::from_str(&content)?;
54 } else {
55 let mut file = OpenOptions::new()
56 .write(true)
57 .truncate(true)
58 .create(true)
59 .open(config.as_os_str())?;
60
61 write!(file, "{}", serde_yaml::to_string(&main)?)?;
62 }
63
64 Ok(Self { main, commands })
65 } 26 }
66} 27}
67 28
src/app/config/main.rs +50
@@ -1,5 +1,13 @@
1use std::{error::Error, fs::{self, OpenOptions}, io::Write};
2
1use serde::{Deserialize, Serialize}; 3use serde::{Deserialize, Serialize};
2 4
5#[derive(Clone, Debug, Serialize, Deserialize)]
6pub struct MainConfigTransitional {
7 pub yt_dl: Option<YtDlConfig>,
8 pub max_watch_history: Option<usize>,
9}
10
3#[derive(Clone, Debug, Serialize, Deserialize)] 11#[derive(Clone, Debug, Serialize, Deserialize)]
4pub struct MainConfig { 12pub struct MainConfig {
5 pub yt_dl: YtDlConfig, 13 pub yt_dl: YtDlConfig,
@@ -29,3 +37,45 @@ impl Default for YtDlConfig {
29 } 37 }
30 } 38 }
31} 39}
40
41impl From<MainConfigTransitional> for MainConfig {
42 fn from(config: MainConfigTransitional) -> Self {
43 let mut out = MainConfig::default();
44
45 if let Some(yt_dl) = config.yt_dl {
46 out.yt_dl = yt_dl;
47 }
48
49 if let Some(max_watch_history) = config.max_watch_history {
50 out.max_watch_history = max_watch_history;
51 }
52
53 out
54 }
55}
56
57impl MainConfig {
58 pub fn load() -> Result<Self, Box<dyn Error>> {
59 let mut config = home::home_dir().expect("Cannot get your home directory");
60 let mut main = MainConfig::default();
61 config.push(".config");
62 config.push("youtube-tui");
63 config.push("main.yml");
64
65 if config.exists() {
66 let content = fs::read_to_string(config.as_os_str())?;
67 let main_transitional: MainConfigTransitional = serde_yaml::from_str(&content)?;
68 main = main_transitional.into();
69 }
70
71 let mut file = OpenOptions::new()
72 .write(true)
73 .truncate(true)
74 .create(true)
75 .open(config.as_os_str())?;
76
77 write!(file, "{}", serde_yaml::to_string(&main)?)?;
78
79 Ok(main)
80 }
81}\ No newline at end of file
src/app/pages/global.rs +25 −20
@@ -12,7 +12,7 @@ use tui::{
12use crate::{ 12use crate::{
13 app::app::App, 13 app::app::App,
14 functions::center_rect, 14 functions::center_rect,
15 structs::{SearchSettings, Page}, 15 structs::{Page, SearchSettings},
16 traits::{KeyInput, SelectItem}, 16 traits::{KeyInput, SelectItem},
17 widgets::{force_clear::ForceClear, horizontal_split::HorizontalSplit}, 17 widgets::{force_clear::ForceClear, horizontal_split::HorizontalSplit},
18}; 18};
@@ -83,25 +83,30 @@ impl KeyInput for GlobalItem {
83 app.search_text.pop(); 83 app.search_text.pop();
84 } 84 }
85 KeyCode::Enter => { 85 KeyCode::Enter => {
86 let state = Search::default(); 86 if app.search_text.len() == 0 {
87 let mut history = app.history.clone(); 87 *app.message.lock().unwrap() =
88 let search_text = app.search_text.clone(); 88 Some(String::from("Search term cannot be empty"));
89 let search_settings = app.search_settings.clone(); 89 } else {
90 history.push(app.into()); 90 let state = Search::default();
91 91 let mut history = app.history.clone();
92 return ( 92 let search_text = app.search_text.clone();
93 false, 93 let search_settings = app.search_settings.clone();
94 App { 94 history.push(app.into());
95 history, 95
96 page: Page::Search, 96 return (
97 selectable: App::selectable(&state), 97 false,
98 state, 98 App {
99 search_text, 99 history,
100 search_settings, 100 page: Page::Search,
101 load: true, 101 selectable: App::selectable(&state),
102 ..Default::default() 102 state,
103 }, 103 search_text,
104 ); 104 search_settings,
105 load: true,
106 ..Default::default()
107 },
108 );
109 }
105 } 110 }
106 _ => {} 111 _ => {}
107 }, 112 },
src/app/pages/item_info.rs +453 −38
@@ -1,5 +1,6 @@
1use std::{ 1use std::{
2 collections::LinkedList, 2 collections::LinkedList,
3 error::Error,
3 process::Command, 4 process::Command,
4 sync::{Arc, Mutex}, 5 sync::{Arc, Mutex},
5 thread, 6 thread,
@@ -8,8 +9,8 @@ use std::{
8use crate::{ 9use crate::{
9 app::{app::App, config::EnvVar, pages::global::*}, 10 app::{app::App, config::EnvVar, pages::global::*},
10 functions::download_all_thumbnails, 11 functions::download_all_thumbnails,
11 structs::{FullVideo, Item, ListItem, Page, Row, RowItem}, 12 structs::{FullPlayList, FullVideo, Item, ListItem, Page, Row, RowItem, WatchHistory},
12 traits::{KeyInput, LoadItem, SelectItem}, 13 traits::{KeyInput, SelectItem},
13 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList}, 14 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
14}; 15};
15use crossterm::event::KeyCode; 16use crossterm::event::KeyCode;
@@ -26,6 +27,7 @@ use super::global::GlobalItem;
26pub enum ItemInfoItem { 27pub enum ItemInfoItem {
27 Unknown, 28 Unknown,
28 Video(VideoItemInfo), 29 Video(VideoItemInfo),
30 PlayList(PlayListItemInfo),
29} 31}
30 32
31#[derive(Debug, Clone)] 33#[derive(Debug, Clone)]
@@ -35,6 +37,30 @@ pub struct VideoItemInfo {
35 mode: Mode, 37 mode: Mode,
36} 38}
37 39
40#[derive(Debug, Clone)]
41pub struct PlayListItemInfo {
42 playlist: FullPlayList,
43 video_view_list: TextList,
44 playlist_view_list: TextList,
45 display_view: PlayListDisplayView,
46 mode: Mode,
47}
48
49#[derive(Debug, Clone, Copy)]
50pub enum PlayListDisplayView {
51 VideoList,
52 PlayListView,
53}
54
55impl PlayListDisplayView {
56 pub fn toggle(self) -> Self {
57 match self {
58 PlayListDisplayView::VideoList => PlayListDisplayView::PlayListView,
59 PlayListDisplayView::PlayListView => PlayListDisplayView::VideoList,
60 }
61 }
62}
63
38impl SelectItem for ItemInfoItem { 64impl SelectItem for ItemInfoItem {
39 fn select(&mut self, app: App) -> (App, bool) { 65 fn select(&mut self, app: App) -> (App, bool) {
40 let selected = true; 66 let selected = true;
@@ -48,7 +74,7 @@ impl SelectItem for ItemInfoItem {
48} 74}
49 75
50impl KeyInput for ItemInfoItem { 76impl KeyInput for ItemInfoItem {
51 fn key_input(&mut self, key: KeyCode, mut app: App) -> (bool, App) { 77 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
52 match self { 78 match self {
53 ItemInfoItem::Video(videoinfo) => match key { 79 ItemInfoItem::Video(videoinfo) => match key {
54 KeyCode::Up => videoinfo.list.up(), 80 KeyCode::Up => videoinfo.list.up(),
@@ -62,11 +88,6 @@ impl KeyInput for ItemInfoItem {
62 88
63 match videoinfo.list.selected { 89 match videoinfo.list.selected {
64 0 => { 90 0 => {
65 app.watch_history.push(
66 videoinfo.video.video_id.clone(),
67 ListItem::FullVideo(videoinfo.video.clone()),
68 &app.config,
69 );
70 let command = 91 let command =
71 match app.config.commands.video_player.clone().as_command_vec( 92 match app.config.commands.video_player.clone().as_command_vec(
72 EnvVar { 93 EnvVar {
@@ -99,11 +120,6 @@ impl KeyInput for ItemInfoItem {
99 run_command(command, app.message.clone()); 120 run_command(command, app.message.clone());
100 } 121 }
101 1 => { 122 1 => {
102 app.watch_history.push(
103 videoinfo.video.video_id.clone(),
104 ListItem::FullVideo(videoinfo.video.clone()),
105 &app.config,
106 );
107 let command = 123 let command =
108 match app.config.commands.audio_player.clone().as_command_vec( 124 match app.config.commands.audio_player.clone().as_command_vec(
109 EnvVar { 125 EnvVar {
@@ -136,11 +152,6 @@ impl KeyInput for ItemInfoItem {
136 run_command(command, app.message.clone()); 152 run_command(command, app.message.clone());
137 } 153 }
138 2 => { 154 2 => {
139 app.watch_history.push(
140 videoinfo.video.video_id.clone(),
141 ListItem::FullVideo(videoinfo.video.clone()),
142 &app.config,
143 );
144 let command = 155 let command =
145 match app.config.commands.video_downloader.clone().as_command_vec( 156 match app.config.commands.video_downloader.clone().as_command_vec(
146 EnvVar { 157 EnvVar {
@@ -173,11 +184,6 @@ impl KeyInput for ItemInfoItem {
173 run_command(command, app.message.clone()); 184 run_command(command, app.message.clone());
174 } 185 }
175 3 => { 186 3 => {
176 app.watch_history.push(
177 videoinfo.video.video_id.clone(),
178 ListItem::FullVideo(videoinfo.video.clone()),
179 &app.config,
180 );
181 let command = 187 let command =
182 match app.config.commands.audio_downloader.clone().as_command_vec( 188 match app.config.commands.audio_downloader.clone().as_command_vec(
183 EnvVar { 189 EnvVar {
@@ -216,11 +222,6 @@ impl KeyInput for ItemInfoItem {
216 dir.push("youtube-tui"); 222 dir.push("youtube-tui");
217 dir.push("thumbnails"); 223 dir.push("thumbnails");
218 dir.push(format!("{}.png", videoinfo.video.video_id)); 224 dir.push(format!("{}.png", videoinfo.video.video_id));
219 // let command = vec![
220 // String::from("mpv"),
221 // String::from("--no-terminal"),
222 // (*dir.as_path().to_string_lossy()).to_string(),
223 // ];
224 225
225 let command = 226 let command =
226 match app.config.commands.image_viewer.clone().as_command_vec( 227 match app.config.commands.image_viewer.clone().as_command_vec(
@@ -254,6 +255,301 @@ impl KeyInput for ItemInfoItem {
254 } 255 }
255 _ => {} 256 _ => {}
256 }, 257 },
258
259 ItemInfoItem::PlayList(playlistinfo) => match playlistinfo.display_view {
260 PlayListDisplayView::PlayListView => match key {
261 KeyCode::Up => playlistinfo.playlist_view_list.up(),
262 KeyCode::Down => playlistinfo.playlist_view_list.down(),
263 KeyCode::PageUp => playlistinfo.playlist_view_list.selected = 0,
264 KeyCode::PageDown => {
265 playlistinfo.playlist_view_list.selected =
266 playlistinfo.playlist_view_list.items.len() - 1
267 }
268 KeyCode::Enter => {
269 if playlistinfo.playlist_view_list.selected > 0
270 && playlistinfo.playlist_view_list.selected < 7
271 {
272 *app.message.lock().unwrap() =
273 Some(String::from("Launched application"));
274 }
275
276 match playlistinfo.playlist_view_list.selected {
277 0 => {
278 playlistinfo.display_view = playlistinfo.display_view.toggle();
279 }
280
281 1 => {
282 let command = match app
283 .config
284 .commands
285 .playlist_video_all
286 .clone()
287 .as_command_vec(
288 EnvVar {
289 url: Some(match playlistinfo.mode {
290 Mode::Youtube => {
291 format!(
292 "https://www.youtube.com/playlist?list={}",
293 playlistinfo.playlist.playlist_id
294 )
295 }
296 Mode::Invidious => {
297 format!(
298 "{}/playlist?list={}",
299 app.client.server,
300 playlistinfo.playlist.playlist_id
301 )
302 }
303 }),
304 ..Default::default()
305 },
306 &app.config,
307 ) {
308 Ok(command) => command,
309 Err(_) => {
310 *app.message.lock().unwrap() =
311 Some(String::from("Error in parsing launch command"));
312 return (false, app);
313 }
314 };
315
316 run_command(command, app.message.clone());
317 }
318
319 2 => {
320 let command = match app
321 .config
322 .commands
323 .playlist_audio_all
324 .clone()
325 .as_command_vec(
326 EnvVar {
327 url: Some(match playlistinfo.mode {
328 Mode::Youtube => {
329 format!(
330 "https://www.youtube.com/playlist?list={}",
331 playlistinfo.playlist.playlist_id
332 )
333 }
334 Mode::Invidious => {
335 format!(
336 "{}/playlist?list={}",
337 app.client.server,
338 playlistinfo.playlist.playlist_id
339 )
340 }
341 }),
342 ..Default::default()
343 },
344 &app.config,
345 ) {
346 Ok(command) => command,
347 Err(_) => {
348 *app.message.lock().unwrap() =
349 Some(String::from("Error in parsing launch command"));
350 return (false, app);
351 }
352 };
353
354 run_command(command, app.message.clone());
355 }
356
357 3 => {
358 let command = match app
359 .config
360 .commands
361 .playlist_shuffle_audio_all
362 .clone()
363 .as_command_vec(
364 EnvVar {
365 url: Some(match playlistinfo.mode {
366 Mode::Youtube => {
367 format!(
368 "https://www.youtube.com/playlist?list={}",
369 playlistinfo.playlist.playlist_id
370 )
371 }
372 Mode::Invidious => {
373 format!(
374 "{}/playlist?list={}",
375 app.client.server,
376 playlistinfo.playlist.playlist_id
377 )
378 }
379 }),
380 ..Default::default()
381 },
382 &app.config,
383 ) {
384 Ok(command) => command,
385 Err(_) => {
386 *app.message.lock().unwrap() =
387 Some(String::from("Error in parsing launch command"));
388 return (false, app);
389 }
390 };
391
392 run_command(command, app.message.clone());
393 }
394
395 4 => {
396 let command = match app
397 .config
398 .commands
399 .download_all_video
400 .clone()
401 .as_command_vec(
402 EnvVar {
403 url: Some(match playlistinfo.mode {
404 Mode::Youtube => {
405 format!(
406 "https://www.youtube.com/playlist?list={}",
407 playlistinfo.playlist.playlist_id
408 )
409 }
410 Mode::Invidious => {
411 format!(
412 "{}/playlist?list={}",
413 app.client.server,
414 playlistinfo.playlist.playlist_id
415 )
416 }
417 }),
418 ..Default::default()
419 },
420 &app.config,
421 ) {
422 Ok(command) => command,
423 Err(_) => {
424 *app.message.lock().unwrap() =
425 Some(String::from("Error in parsing launch command"));
426 return (false, app);
427 }
428 };
429
430 run_command(command, app.message.clone());
431 }
432
433 5 => {
434 let command = match app
435 .config
436 .commands
437 .download_all_audio
438 .clone()
439 .as_command_vec(
440 EnvVar {
441 url: Some(match playlistinfo.mode {
442 Mode::Youtube => {
443 format!(
444 "https://www.youtube.com/playlist?list={}",
445 playlistinfo.playlist.playlist_id
446 )
447 }
448 Mode::Invidious => {
449 format!(
450 "{}/playlist?list={}",
451 app.client.server,
452 playlistinfo.playlist.playlist_id
453 )
454 }
455 }),
456 ..Default::default()
457 },
458 &app.config,
459 ) {
460 Ok(command) => command,
461 Err(_) => {
462 *app.message.lock().unwrap() =
463 Some(String::from("Error in parsing launch command"));
464 return (false, app);
465 }
466 };
467
468 run_command(command, app.message.clone());
469 }
470
471 6 => {
472 let mut dir = home::home_dir().unwrap();
473
474 dir.push(".cache");
475 dir.push("youtube-tui");
476 dir.push("thumbnails");
477 dir.push(format!("{}.png", playlistinfo.playlist.playlist_id));
478
479 let command =
480 match app.config.commands.image_viewer.clone().as_command_vec(
481 EnvVar {
482 url: Some(
483 (*dir.as_path().to_string_lossy()).to_string(),
484 ),
485 ..Default::default()
486 },
487 &app.config,
488 ) {
489 Ok(command) => command,
490 Err(_) => {
491 *app.message.lock().unwrap() = Some(String::from(
492 "Error in parsing launch command",
493 ));
494 return (false, app);
495 }
496 };
497
498 run_command(command, app.message.clone());
499 }
500
501 7 => {
502 *app.message.lock().unwrap() = Some(String::from(
503 "Too lazy to implement that what do you expect?",
504 ));
505 }
506
507 8 => {
508 playlistinfo.mode.toggle();
509 }
510
511 _ => {}
512 }
513 }
514
515 _ => {}
516 },
517 PlayListDisplayView::VideoList => match key {
518 KeyCode::Up => playlistinfo.video_view_list.up(),
519 KeyCode::Down => playlistinfo.video_view_list.down(),
520 KeyCode::PageUp => playlistinfo.video_view_list.selected = 0,
521 KeyCode::PageDown => {
522 playlistinfo.video_view_list.selected =
523 playlistinfo.video_view_list.items.len() - 1
524 }
525 KeyCode::Enter => match playlistinfo.video_view_list.selected {
526 0 => {
527 playlistinfo.display_view = playlistinfo.display_view.toggle();
528 }
529
530 x => {
531 let state = ItemInfo::default();
532 let mut history = app.history.clone();
533 history.push(app.into());
534
535 return (
536 false,
537 App {
538 history,
539 page: Page::ItemDisplay(DisplayItem::Video(
540 playlistinfo.playlist.videos[x - 1].video_id.clone(),
541 )),
542 selectable: App::selectable(&state),
543 state,
544 ..Default::default()
545 },
546 );
547 }
548 },
549
550 _ => {}
551 },
552 },
257 _ => {} 553 _ => {}
258 } 554 }
259 555
@@ -261,8 +557,12 @@ impl KeyInput for ItemInfoItem {
261 } 557 }
262} 558}
263 559
264impl LoadItem for ItemInfoItem { 560impl ItemInfoItem {
265 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn std::error::Error>> { 561 pub fn load_item(
562 &self,
563 app: &App,
564 watch_history: &mut WatchHistory,
565 ) -> Result<Box<Self>, Box<dyn Error>> {
266 let mut this = self.clone(); 566 let mut this = self.clone();
267 567
268 if let ItemInfoItem::Unknown = this { 568 if let ItemInfoItem::Unknown = this {
@@ -284,11 +584,66 @@ impl LoadItem for ItemInfoItem {
284 String::from("Visit channel"), 584 String::from("Visit channel"),
285 String::from("Mode placeholder"), 585 String::from("Mode placeholder"),
286 ]); 586 ]);
287 this = ItemInfoItem::Video(VideoItemInfo { 587
588 let iteminfo = VideoItemInfo {
288 video, 589 video,
289 list, 590 list,
290 mode: Mode::Youtube, 591 mode: Mode::Youtube,
291 }); 592 };
593
594 watch_history.push(
595 iteminfo.video.video_id.clone(),
596 ListItem::FullVideo(iteminfo.video.clone()),
597 &app.config,
598 );
599
600 this = ItemInfoItem::Video(iteminfo);
601 }
602
603 DisplayItem::PlayList(id) => {
604 let mut videos_text_list = TextList::default();
605 let mut playlist_text_list = TextList::default();
606 let playlist: FullPlayList = app.client.playlist(id, None)?.into();
607 let _ = download_all_thumbnails(
608 playlist
609 .videos
610 .iter()
611 .map(|v| (v.video_thumbnail.clone(), v.video_id.clone()))
612 .collect(),
613 );
614
615 videos_text_list.items = vec![String::from("Swtich view")];
616 videos_text_list
617 .items
618 .extend(playlist.videos.iter().map(|v| v.title.clone()));
619
620 playlist_text_list.items(vec![
621 String::from("Switch view"),
622 String::from("Watch all"),
623 String::from("Play all audio"),
624 String::from("Shuffle play all audio"),
625 String::from("Download all video"),
626 String::from("Download all audio"),
627 String::from("View thumbnail"),
628 String::from("Visit channel"),
629 String::from("Mode placeholder"),
630 ]);
631
632 let iteminfo = PlayListItemInfo {
633 playlist: playlist,
634 video_view_list: videos_text_list,
635 playlist_view_list: playlist_text_list,
636 mode: Mode::Youtube,
637 display_view: PlayListDisplayView::PlayListView,
638 };
639
640 watch_history.push(
641 iteminfo.playlist.playlist_id.clone(),
642 ListItem::FullPlayList(iteminfo.playlist.clone()),
643 &app.config,
644 );
645
646 this = ItemInfoItem::PlayList(iteminfo);
292 } 647 }
293 }, 648 },
294 649
@@ -297,9 +652,7 @@ impl LoadItem for ItemInfoItem {
297 } 652 }
298 Ok(Box::new(this)) 653 Ok(Box::new(this))
299 } 654 }
300}
301 655
302impl ItemInfoItem {
303 pub fn render_item<B: Backend>( 656 pub fn render_item<B: Backend>(
304 &mut self, 657 &mut self,
305 frame: &mut Frame<B>, 658 frame: &mut Frame<B>,
@@ -347,6 +700,60 @@ impl ItemInfoItem {
347 frame.render_widget(list, chunks[1]); 700 frame.render_widget(list, chunks[1]);
348 } 701 }
349 702
703 ItemInfoItem::PlayList(playlistinfo) => {
704 let split = HorizontalSplit::default()
705 .percentages(vec![40, 60])
706 .border_style(Style::default().fg(if selected {
707 Color::LightBlue
708 } else if hover {
709 Color::LightRed
710 } else {
711 Color::Reset
712 }));
713
714 let chunks = split.inner(rect);
715
716 frame.render_widget(split, rect);
717
718 if !popup_focus {
719 let item_display = ItemDisplay {
720 item: ListItem::FullPlayList(playlistinfo.playlist.clone()),
721 };
722
723 frame.render_widget(item_display, chunks[0]);
724 }
725
726 match playlistinfo.display_view {
727 PlayListDisplayView::VideoList => {
728 let mut list = playlistinfo.video_view_list.clone();
729 list.area(chunks[1]);
730 if selected {
731 list.selected_style(Style::default().fg(Color::LightRed));
732 } else {
733 list.selected_style(Style::default().fg(Color::LightYellow));
734 }
735
736 frame.render_widget(list, chunks[1]);
737 }
738 PlayListDisplayView::PlayListView => {
739 let index = playlistinfo.playlist_view_list.items.len() - 1;
740 playlistinfo.playlist_view_list.items[index] =
741 format!("Mode: {}", playlistinfo.mode);
742 drop(index);
743
744 let mut list = playlistinfo.playlist_view_list.clone();
745 list.area(chunks[1]);
746 if selected {
747 list.selected_style(Style::default().fg(Color::LightRed));
748 } else {
749 list.selected_style(Style::default().fg(Color::LightYellow));
750 }
751
752 frame.render_widget(list, chunks[1]);
753 }
754 }
755 }
756
350 ItemInfoItem::Unknown => { 757 ItemInfoItem::Unknown => {
351 let split = HorizontalSplit::default() 758 let split = HorizontalSplit::default()
352 .percentages(vec![40, 60]) 759 .percentages(vec![40, 60])
@@ -357,6 +764,7 @@ impl ItemInfoItem {
357 } else { 764 } else {
358 Color::Reset 765 Color::Reset
359 })); 766 }));
767
360 frame.render_widget(split, rect); 768 frame.render_widget(split, rect);
361 } 769 }
362 } 770 }
@@ -366,6 +774,7 @@ impl ItemInfoItem {
366#[derive(Debug, Clone, PartialEq)] 774#[derive(Debug, Clone, PartialEq)]
367pub enum DisplayItem { 775pub enum DisplayItem {
368 Video(String), 776 Video(String),
777 PlayList(String),
369} 778}
370 779
371pub struct ItemInfo; 780pub struct ItemInfo;
@@ -382,10 +791,16 @@ impl ItemInfo {
382 pub fn default() -> Vec<Row> { 791 pub fn default() -> Vec<Row> {
383 vec![ 792 vec![
384 Row { 793 Row {
385 items: vec![RowItem { 794 items: vec![
386 item: Item::Global(GlobalItem::SearchBar), 795 RowItem {
387 constraint: Constraint::Percentage(100), 796 item: Item::Global(GlobalItem::SearchBar),
388 }], 797 constraint: Constraint::Min(16),
798 },
799 RowItem {
800 item: Item::Global(GlobalItem::SearchSettings),
801 constraint: Constraint::Length(5),
802 },
803 ],
389 centered: false, 804 centered: false,
390 height: Constraint::Length(3), 805 height: Constraint::Length(3),
391 }, 806 },
src/app/pages/main_menu.rs +36 −16
@@ -7,7 +7,7 @@ use crate::{
7 }, 7 },
8 functions::download_all_thumbnails, 8 functions::download_all_thumbnails,
9 structs::{Item, ListItem, Page, Row, RowItem}, 9 structs::{Item, ListItem, Page, Row, RowItem},
10 traits::{KeyInput, LoadItem, SelectItem}, 10 traits::{KeyInput, SelectItem},
11 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList}, 11 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
12}; 12};
13use crossterm::event::KeyCode; 13use crossterm::event::KeyCode;
@@ -52,11 +52,11 @@ impl SelectItem for MainMenuItem {
52impl KeyInput for MainMenuItem { 52impl KeyInput for MainMenuItem {
53 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) { 53 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
54 match self { 54 match self {
55 MainMenuItem::VideoList(Some((video_list, list, _))) => match key { 55 MainMenuItem::VideoList(Some((list, textlist, _))) => match key {
56 KeyCode::Up => list.up(), 56 KeyCode::Up => textlist.up(),
57 KeyCode::Down => list.down(), 57 KeyCode::Down => textlist.down(),
58 KeyCode::PageUp => list.selected = 0, 58 KeyCode::PageUp => textlist.selected = 0,
59 KeyCode::PageDown => list.selected = list.items.len() - 1, 59 KeyCode::PageDown => textlist.selected = textlist.items.len() - 1,
60 KeyCode::Enter => { 60 KeyCode::Enter => {
61 let state = ItemInfo::default(); 61 let state = ItemInfo::default();
62 let mut history = app.history.clone(); 62 let mut history = app.history.clone();
@@ -66,9 +66,31 @@ impl KeyInput for MainMenuItem {
66 false, 66 false,
67 App { 67 App {
68 history, 68 history,
69 page: Page::ItemDisplay(DisplayItem::Video( 69 page: Page::ItemDisplay(
70 video_list.iter().nth(list.selected).unwrap().id(), 70 match list.iter().nth(textlist.selected).unwrap() {
71 )), 71 ListItem::FullVideo(item) => {
72 DisplayItem::Video(
73 item.video_id.clone(),
74 )
75 }
76 ListItem::FullPlayList(item) => {
77 DisplayItem::PlayList(
78 item.playlist_id.clone(),
79 )
80 }
81 ListItem::MiniPlayList(item) => {
82 DisplayItem::PlayList(
83 item.playlist_id.clone(),
84 )
85 }
86 ListItem::MiniVideo(item) => {
87 DisplayItem::Video(
88 item.video_id.clone(),
89 )
90 }
91 _ => unreachable!(),
92 },
93 ),
72 selectable: App::selectable(&state), 94 selectable: App::selectable(&state),
73 state, 95 state,
74 ..Default::default() 96 ..Default::default()
@@ -84,8 +106,8 @@ impl KeyInput for MainMenuItem {
84 } 106 }
85} 107}
86 108
87impl LoadItem for MainMenuItem { 109impl MainMenuItem {
88 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn Error>> { 110 pub fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn Error>> {
89 let mut this = self.clone(); 111 let mut this = self.clone();
90 112
91 match &mut this { 113 match &mut this {
@@ -132,7 +154,7 @@ impl LoadItem for MainMenuItem {
132 .map(|t| ListItem::MiniVideo(t.into())) 154 .map(|t| ListItem::MiniVideo(t.into()))
133 .collect(); 155 .collect();
134 156
135 download_all_thumbnails( 157 let _ = download_all_thumbnails(
136 list.iter() 158 list.iter()
137 .map(|t| match t { 159 .map(|t| match t {
138 ListItem::MiniVideo(v) => { 160 ListItem::MiniVideo(v) => {
@@ -141,7 +163,7 @@ impl LoadItem for MainMenuItem {
141 _ => unreachable!(), 163 _ => unreachable!(),
142 }) 164 })
143 .collect(), 165 .collect(),
144 )?; 166 );
145 167
146 let mut text_list = TextList::default(); 168 let mut text_list = TextList::default();
147 169
@@ -165,7 +187,7 @@ impl LoadItem for MainMenuItem {
165 home::home_dir() 187 home::home_dir()
166 .expect("Cannot get your home directory") 188 .expect("Cannot get your home directory")
167 .join(".local/share/youtube-tui/watch_history/info") 189 .join(".local/share/youtube-tui/watch_history/info")
168 .join(format!("{}.json", t)), 190 .join(format!("{}.json", t.id())),
169 ); 191 );
170 192
171 if let Ok(file) = file { 193 if let Ok(file) = file {
@@ -189,9 +211,7 @@ impl LoadItem for MainMenuItem {
189 211
190 Ok(Box::new(this)) 212 Ok(Box::new(this))
191 } 213 }
192}
193 214
194impl MainMenuItem {
195 pub fn render_item<B: Backend>( 215 pub fn render_item<B: Backend>(
196 &mut self, 216 &mut self,
197 frame: &mut Frame<B>, 217 frame: &mut Frame<B>,
src/app/pages/search.rs +101 −72
@@ -1,4 +1,4 @@
1use std::collections::LinkedList; 1use std::{collections::LinkedList, error::Error};
2 2
3use crossterm::event::KeyCode; 3use crossterm::event::KeyCode;
4use invidious::structs::hidden::SearchItem as InvidiousSearchItem; 4use invidious::structs::hidden::SearchItem as InvidiousSearchItem;
@@ -12,8 +12,8 @@ use tui::{
12use crate::{ 12use crate::{
13 app::app::App, 13 app::app::App,
14 functions::download_all_thumbnails, 14 functions::download_all_thumbnails,
15 structs::{Item, ListItem, MiniVideo, Page, Row, RowItem}, 15 structs::{Item, ListItem, MiniPlayList, MiniVideo, Page, Row, RowItem},
16 traits::{KeyInput, LoadItem, SelectItem}, 16 traits::{KeyInput, SelectItem},
17 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList}, 17 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
18}; 18};
19 19
@@ -104,6 +104,25 @@ impl KeyInput for SearchItem {
104 ); 104 );
105 } 105 }
106 106
107 ListItem::MiniPlayList(playlist) => {
108 let state = ItemInfo::default();
109 let mut history = app.history.clone();
110 history.push(app.into());
111
112 return (
113 false,
114 App {
115 history,
116 page: Page::ItemDisplay(DisplayItem::PlayList(
117 playlist.playlist_id.clone(),
118 )),
119 selectable: App::selectable(&state),
120 state,
121 ..Default::default()
122 },
123 );
124 }
125
107 _ => {} 126 _ => {}
108 } 127 }
109 } 128 }
@@ -116,99 +135,110 @@ impl KeyInput for SearchItem {
116 } 135 }
117} 136}
118 137
119impl LoadItem for SearchItem { 138impl SearchItem {
120 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn std::error::Error>> { 139 pub fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn Error>> {
121 let mut this = self.clone(); 140 let mut this = self.clone();
122 141
123 match &mut this { 142 match &mut this {
124 SearchItem::Search { results, text_list } => { 143 SearchItem::Search { results, text_list } => {
125 // panic!("got here"); 144 // panic!("got here");
126 if app.search_text.len() == 0 {
127 *app.message.lock().unwrap() =
128 Some(String::from("Search term cannot be empty"));
129 } else {
130 let mut args = vec![app.search_text.clone()];
131 args.extend(app.search_settings.clone().to_vec());
132
133 let invidious_results = app
134 .client
135 .search(Some(&format!(
136 "page={}&q={}",
137 app.page_no,
138 args.join("&").as_str()
139 )))?
140 .items;
141
142 let mut items = LinkedList::new();
143
144 for item in invidious_results {
145 match item {
146 InvidiousSearchItem::Video {
147 title: _,
148 videoId: _,
149 author: _,
150 authorId: _,
151 authorUrl: _,
152 lengthSeconds: _,
153 videoThumbnails: _,
154 description: _,
155 descriptionHtml: _,
156 viewCount: _,
157 published: _,
158 publishedText: _,
159 liveNow: _,
160 paid: _,
161 premium: _,
162 } => {
163 items.push_back(ListItem::MiniVideo(MiniVideo::from(item)));
164 }
165 145
166 _ => {} 146 let mut args = vec![app.search_text.clone()];
147 args.extend(app.search_settings.clone().to_vec());
148
149 let invidious_results = app
150 .client
151 .search(Some(&format!(
152 "page={}&q={}",
153 app.page_no,
154 args.join("&").as_str()
155 )))?
156 .items;
157
158 let mut items = LinkedList::new();
159
160 for item in invidious_results {
161 match item {
162 InvidiousSearchItem::Video {
163 title: _,
164 videoId: _,
165 author: _,
166 authorId: _,
167 authorUrl: _,
168 lengthSeconds: _,
169 videoThumbnails: _,
170 description: _,
171 descriptionHtml: _,
172 viewCount: _,
173 published: _,
174 publishedText: _,
175 liveNow: _,
176 paid: _,
177 premium: _,
178 } => {
179 items.push_back(ListItem::MiniVideo(MiniVideo::from(item)));
167 } 180 }
168 }
169 181
170 let mut minimum_length = 0; 182 InvidiousSearchItem::Playlist {
183 title: _,
184 playlistId: _,
185 author: _,
186 authorId: _,
187 authorUrl: _,
188 videoCount: _,
189 videos: _,
190 } => {
191 items.push_back(ListItem::MiniPlayList(MiniPlayList::from(item)));
192 }
171 193
172 if app.page_no != 1 { 194 _ => {}
173 minimum_length += 1;
174 items.push_front(ListItem::PageTurner(false));
175 } 195 }
196 }
176 197
177 if items.len() == minimum_length { 198 let mut minimum_length = 0;
178 *app.message.lock().unwrap() = Some(String::from("No results found"));
179 } else {
180 items.push_back(ListItem::PageTurner(true));
181 }
182 199
183 text_list.items = textlist_from_video_list(&items); 200 if app.page_no != 1 {
201 minimum_length += 1;
202 items.push_front(ListItem::PageTurner(false));
203 }
184 204
185 let mut thumbnails = LinkedList::new(); 205 if items.len() == minimum_length {
206 *app.message.lock().unwrap() = Some(String::from("No results found"));
207 } else {
208 items.push_back(ListItem::PageTurner(true));
209 }
186 210
187 for item in items.iter() { 211 text_list.items = textlist_from_video_list(&items);
188 match item {
189 ListItem::MiniVideo(video) => {
190 thumbnails.push_back((
191 video.video_thumbnail.clone(),
192 video.video_id.clone(),
193 ));
194 }
195 212
196 _ => {} 213 let mut thumbnails = LinkedList::new();
214
215 for item in items.iter() {
216 match item {
217 ListItem::MiniVideo(video) => {
218 thumbnails
219 .push_back((video.video_thumbnail.clone(), video.video_id.clone()));
197 } 220 }
198 }
199 221
200 let _ = download_all_thumbnails(thumbnails); 222 ListItem::MiniPlayList(playlist) => {
223 if let Some(thumbnail) = &playlist.thumbnail {
224 thumbnails
225 .push_back((thumbnail.clone(), playlist.playlist_id.clone()));
226 }
227 }
201 228
202 *results = Some(items); 229 _ => {}
230 }
203 } 231 }
232
233 let _ = download_all_thumbnails(thumbnails);
234
235 *results = Some(items);
204 } 236 }
205 } 237 }
206 238
207 Ok(Box::new(this)) 239 Ok(Box::new(this))
208 } 240 }
209}
210 241
211impl SearchItem {
212 pub fn render_item<B: Backend>( 242 pub fn render_item<B: Backend>(
213 &mut self, 243 &mut self,
214 frame: &mut Frame<B>, 244 frame: &mut Frame<B>,
@@ -217,7 +247,6 @@ impl SearchItem {
217 hover: bool, 247 hover: bool,
218 popup_focus: bool, 248 popup_focus: bool,
219 ) { 249 ) {
220
221 match self { 250 match self {
222 SearchItem::Search { results, text_list } => { 251 SearchItem::Search { results, text_list } => {
223 let split = HorizontalSplit::default() 252 let split = HorizontalSplit::default()
src/functions/download_all_thumbnails.rs +1 −1
@@ -5,7 +5,7 @@ use tokio::runtime::Runtime;
5 5
6pub enum ItemType { 6pub enum ItemType {
7 Video, 7 Video,
8 Playlist, 8 PlayList,
9} 9}
10 10
11pub fn download_all_thumbnails( 11pub fn download_all_thumbnails(
src/main.rs +18 −16
@@ -14,7 +14,6 @@ use youtube_tui::{
14 pages::{item_info::ItemInfo, main_menu::MainMenu, search::Search}, 14 pages::{item_info::ItemInfo, main_menu::MainMenu, search::Search},
15 }, 15 },
16 structs::{Item, Page, Row, RowItem}, 16 structs::{Item, Page, Row, RowItem},
17 traits::LoadItem,
18}; 17};
19 18
20fn main() -> Result<(), Box<dyn Error>> { 19fn main() -> Result<(), Box<dyn Error>> {
@@ -77,21 +76,25 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
77 *app.message.lock().unwrap() = Some(e.to_string()); 76 *app.message.lock().unwrap() = Some(e.to_string());
78 } 77 }
79 }, 78 },
80 Item::ItemInfo(item) => match item.load_item(&app) { 79 Item::ItemInfo(item) => {
81 Ok(new) => { 80 let mut watch_history = app.watch_history.clone();
82 row_vec.push(RowItem { 81 match item.load_item(&app, &mut watch_history) {
83 item: Item::ItemInfo(*new), 82 Ok(new) => {
84 ..*row_item 83 row_vec.push(RowItem {
85 }); 84 item: Item::ItemInfo(*new),
86 } 85 ..*row_item
87 Err(e) => { 86 });
88 row_vec.push(RowItem { 87 }
89 item: Item::ItemInfo(item.clone()), 88 Err(e) => {
90 ..*row_item 89 row_vec.push(RowItem {
91 }); 90 item: Item::ItemInfo(item.clone()),
92 *app.message.lock().unwrap() = Some(e.to_string()); 91 ..*row_item
92 });
93 *app.message.lock().unwrap() = Some(e.to_string());
94 }
93 } 95 }
94 }, 96 app.watch_history = watch_history;
97 }
95 Item::Search(item) => match item.load_item(&app) { 98 Item::Search(item) => match item.load_item(&app) {
96 Ok(new) => { 99 Ok(new) => {
97 row_vec.push(RowItem { 100 row_vec.push(RowItem {
@@ -255,7 +258,6 @@ fn init() -> Result<(), Box<dyn Error>> {
255 fs::create_dir(&dir)?; 258 fs::create_dir(&dir)?;
256 } 259 }
257 260
258
259 Ok(()) 261 Ok(())
260} 262}
261 263
src/structs/fullplaylist.rs added +46
@@ -0,0 +1,46 @@
1use chrono::{DateTime, NaiveDateTime, Utc};
2use invidious::structs::universal::Playlist;
3use serde::{Deserialize, Serialize};
4
5use super::MiniVideo;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct FullPlayList {
9 pub title: String,
10 pub playlist_id: String,
11 pub video_count: usize,
12 pub views: usize,
13 pub updated: String,
14 pub thumbnail: Option<String>,
15 pub description: String,
16 pub author: String,
17 pub author_id: String,
18 pub videos: Vec<MiniVideo>,
19}
20
21impl From<Playlist> for FullPlayList {
22 fn from(original: Playlist) -> Self {
23 Self {
24 title: original.title,
25 playlist_id: original.playlistId,
26 video_count: original.videoCount as usize,
27 views: original.viewCount as usize,
28 updated: {
29 let datetime: DateTime<Utc> = DateTime::from_utc(
30 NaiveDateTime::from_timestamp(original.updated as i64, 0),
31 Utc,
32 );
33 format!(" [{}]", datetime.format("%Y/%m/%d"))
34 },
35 thumbnail: if original.videos.len() == 0 {
36 None
37 } else {
38 Some(original.videos[0].videoThumbnails[4].url.clone())
39 },
40 description: original.description,
41 author: original.author,
42 author_id: original.authorId,
43 videos: original.videos.into_iter().map(MiniVideo::from).collect(),
44 }
45 }
46}
src/structs/listitem.rs +18
@@ -1,10 +1,14 @@
1use crate::structs::{FullVideo, MiniVideo}; 1use crate::structs::{FullVideo, MiniVideo};
2use serde::{Deserialize, Serialize}; 2use serde::{Deserialize, Serialize};
3 3
4use super::{FullPlayList, MiniPlayList};
5
4#[derive(Debug, Clone, Deserialize, Serialize)] 6#[derive(Debug, Clone, Deserialize, Serialize)]
5pub enum ListItem { 7pub enum ListItem {
6 MiniVideo(MiniVideo), 8 MiniVideo(MiniVideo),
7 FullVideo(FullVideo), 9 FullVideo(FullVideo),
10 MiniPlayList(MiniPlayList),
11 FullPlayList(FullPlayList),
8 PageTurner(bool), // true: +1 | false: -1 12 PageTurner(bool), // true: +1 | false: -1
9} 13}
10 14
@@ -13,6 +17,8 @@ impl ListItem {
13 match self { 17 match self {
14 ListItem::MiniVideo(video) => video.video_id.clone(), 18 ListItem::MiniVideo(video) => video.video_id.clone(),
15 ListItem::FullVideo(video) => video.video_id.clone(), 19 ListItem::FullVideo(video) => video.video_id.clone(),
20 ListItem::MiniPlayList(playlist) => playlist.playlist_id.clone(),
21 ListItem::FullPlayList(playlist) => playlist.playlist_id.clone(),
16 _ => { 22 _ => {
17 unreachable!() 23 unreachable!()
18 } 24 }
@@ -40,6 +46,18 @@ impl ListItem {
40 .into_iter() 46 .into_iter()
41 .filter(|c| !c.is_ascii_control()) 47 .filter(|c| !c.is_ascii_control())
42 .collect(), 48 .collect(),
49 ListItem::MiniPlayList(playlist) => playlist
50 .title
51 .chars()
52 .into_iter()
53 .filter(|c| !c.is_ascii_control())
54 .collect(),
55 ListItem::FullPlayList(playlist) => playlist
56 .title
57 .chars()
58 .into_iter()
59 .filter(|c| !c.is_ascii_control())
60 .collect(),
43 ListItem::PageTurner(turner) => { 61 ListItem::PageTurner(turner) => {
44 if *turner { 62 if *turner {
45 String::from("Next Page") 63 String::from("Next Page")
src/structs/miniplaylist.rs added +45
@@ -0,0 +1,45 @@
1use invidious::structs::hidden::SearchItem;
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug, Clone, Deserialize, Serialize)]
5pub struct MiniPlayList {
6 pub title: String,
7 pub playlist_id: String,
8 pub author: String,
9 pub author_id: String,
10 pub author_url: String,
11 pub video_count: usize,
12 pub thumbnail: Option<String>,
13}
14
15impl From<SearchItem> for MiniPlayList {
16 fn from(original: SearchItem) -> Self {
17 match original {
18 SearchItem::Playlist {
19 title,
20 playlistId,
21 author,
22 authorId,
23 authorUrl,
24 videoCount,
25 videos,
26 } => MiniPlayList {
27 title,
28 playlist_id: playlistId,
29 author,
30 author_id: authorId,
31 author_url: authorUrl,
32 video_count: videoCount as usize,
33 thumbnail: if videos.len() == 0 {
34 None
35 } else {
36 Some(videos[0].videoThumbnails[4].url.clone())
37 },
38 },
39
40 _ => {
41 unreachable!()
42 }
43 }
44 }
45}
src/structs/minivideo.rs +33 −16
@@ -1,5 +1,5 @@
1use chrono::{prelude::*, Utc}; 1use chrono::{prelude::*, Utc};
2use invidious::structs::hidden::{PopularItem, TrendingVideo, SearchItem}; 2use invidious::structs::hidden::{PopularItem, TrendingVideo, SearchItem, PlaylistItem};
3use thousands::Separable; 3use thousands::Separable;
4use serde::{Deserialize, Serialize}; 4use serde::{Deserialize, Serialize};
5 5
@@ -9,11 +9,11 @@ pub struct MiniVideo {
9 pub video_id: String, 9 pub video_id: String,
10 pub video_thumbnail: String, 10 pub video_thumbnail: String,
11 pub length: String, 11 pub length: String,
12 pub view_count: String, 12 pub view_count: Option<String>,
13 pub author: String, 13 pub author: String,
14 pub author_url: String, 14 pub author_url: String,
15 pub published: String, 15 pub published: Option<String>,
16 pub description: String, 16 pub description: Option<String>,
17} 17}
18 18
19impl From<TrendingVideo> for MiniVideo { 19impl From<TrendingVideo> for MiniVideo {
@@ -23,10 +23,10 @@ impl From<TrendingVideo> for MiniVideo {
23 video_id: original.videoId, 23 video_id: original.videoId,
24 video_thumbnail: original.videoThumbnails[4].url.clone(), 24 video_thumbnail: original.videoThumbnails[4].url.clone(),
25 length: hrtime::from_sec_padded(original.lengthSeconds as u64), 25 length: hrtime::from_sec_padded(original.lengthSeconds as u64),
26 view_count: original.viewCount.separate_with_commas(), 26 view_count: Some(original.viewCount.separate_with_commas()),
27 author: original.author, 27 author: original.author,
28 author_url: original.authorUrl, 28 author_url: original.authorUrl,
29 published: format!( 29 published: Some(format!(
30 "{}{}", 30 "{}{}",
31 original.publishedText, 31 original.publishedText,
32 if Utc::now().timestamp() - original.published as i64 > 86400 { 32 if Utc::now().timestamp() - original.published as i64 > 86400 {
@@ -38,8 +38,8 @@ impl From<TrendingVideo> for MiniVideo {
38 } else { 38 } else {
39 String::new() 39 String::new()
40 } 40 }
41 ), 41 )),
42 description: original.description, 42 description: Some(original.description),
43 } 43 }
44 } 44 }
45} 45}
@@ -51,10 +51,10 @@ impl From<PopularItem> for MiniVideo {
51 video_id: original.videoId, 51 video_id: original.videoId,
52 video_thumbnail: original.videoThumbnails[5].url.clone(), 52 video_thumbnail: original.videoThumbnails[5].url.clone(),
53 length: hrtime::from_sec_padded(original.lengthSeconds as u64), 53 length: hrtime::from_sec_padded(original.lengthSeconds as u64),
54 view_count: original.viewCount.separate_with_commas(), 54 view_count: Some(original.viewCount.separate_with_commas()),
55 author: original.author, 55 author: original.author,
56 author_url: original.authorUrl, 56 author_url: original.authorUrl,
57 published: format!( 57 published: Some(format!(
58 "{}{}", 58 "{}{}",
59 original.publishedText, 59 original.publishedText,
60 if Utc::now().timestamp() - original.published as i64 > 86400 { 60 if Utc::now().timestamp() - original.published as i64 > 86400 {
@@ -66,8 +66,8 @@ impl From<PopularItem> for MiniVideo {
66 } else { 66 } else {
67 String::new() 67 String::new()
68 } 68 }
69 ), 69 )),
70 description: String::new(), 70 description: None,
71 } 71 }
72 } 72 }
73} 73}
@@ -81,10 +81,10 @@ impl From<SearchItem> for MiniVideo {
81 video_id: videoId, 81 video_id: videoId,
82 video_thumbnail: videoThumbnails[0].url.clone(), 82 video_thumbnail: videoThumbnails[0].url.clone(),
83 length: hrtime::from_sec_padded(lengthSeconds as u64), 83 length: hrtime::from_sec_padded(lengthSeconds as u64),
84 view_count: viewCount.separate_with_commas(), 84 view_count: Some(viewCount.separate_with_commas()),
85 author: author, 85 author: author,
86 author_url: authorUrl, 86 author_url: authorUrl,
87 published: format!( 87 published: Some(format!(
88 "{}{}", 88 "{}{}",
89 publishedText, 89 publishedText,
90 if Utc::now().timestamp() - published as i64 > 86400 { 90 if Utc::now().timestamp() - published as i64 > 86400 {
@@ -96,12 +96,29 @@ impl From<SearchItem> for MiniVideo {
96 } else { 96 } else {
97 String::new() 97 String::new()
98 } 98 }
99 ), 99 )),
100 description: description, 100 description: Some(description),
101 } 101 }
102 } 102 }
103 103
104 _ => unreachable!(), 104 _ => unreachable!(),
105 } 105 }
106 } 106 }
107}
108
109impl From<PlaylistItem> for MiniVideo {
110 fn from(original: PlaylistItem) -> Self {
111 MiniVideo {
112 title: original.title,
113 video_id: original.videoId,
114 video_thumbnail: original.videoThumbnails[4].url.clone(),
115 length: hrtime::from_sec_padded(original.lengthSeconds as u64),
116 view_count: None,
117 author: original.author,
118 author_url: original.authorUrl,
119 published: None,
120 description: None,
121
122 }
123 }
107}\ No newline at end of file 124}\ No newline at end of file
src/structs/mod.rs +7 −1
@@ -20,4 +20,10 @@ mod watchhistory;
20pub use watchhistory::*; 20pub use watchhistory::*;
21 21
22mod search_settings; 22mod search_settings;
23pub use search_settings::*;\ No newline at end of file 23pub use search_settings::*;
24
25mod miniplaylist;
26pub use miniplaylist::*;
27
28mod fullplaylist;
29pub use fullplaylist::*;\ No newline at end of file
src/structs/search_settings.rs +36 −10
@@ -73,10 +73,23 @@ impl SearchSettings {
73 self.select_text_list.up(); 73 self.select_text_list.up();
74 74
75 match self.text_list.selected { 75 match self.text_list.selected {
76 0 => self.sort_by = SearchSettingsSortBy::index_to_value(self.select_text_list.selected), 76 0 => {
77 1 => self.date = SearchSettingsDate::index_to_value(self.select_text_list.selected), 77 self.sort_by =
78 2 => self.duartion = SearchSettingsDuration::index_to_value(self.select_text_list.selected), 78 SearchSettingsSortBy::index_to_value(self.select_text_list.selected)
79 3 => self.r#type = SearchSettingsType::index_to_value(self.select_text_list.selected), 79 }
80 1 => {
81 self.date =
82 SearchSettingsDate::index_to_value(self.select_text_list.selected)
83 }
84 2 => {
85 self.duartion = SearchSettingsDuration::index_to_value(
86 self.select_text_list.selected,
87 )
88 }
89 3 => {
90 self.r#type =
91 SearchSettingsType::index_to_value(self.select_text_list.selected)
92 }
80 _ => {} 93 _ => {}
81 } 94 }
82 } 95 }
@@ -89,10 +102,23 @@ impl SearchSettings {
89 self.select_text_list.down(); 102 self.select_text_list.down();
90 103
91 match self.text_list.selected { 104 match self.text_list.selected {
92 0 => self.sort_by = SearchSettingsSortBy::index_to_value(self.select_text_list.selected), 105 0 => {
93 1 => self.date = SearchSettingsDate::index_to_value(self.select_text_list.selected), 106 self.sort_by =
94 2 => self.duartion = SearchSettingsDuration::index_to_value(self.select_text_list.selected), 107 SearchSettingsSortBy::index_to_value(self.select_text_list.selected)
95 3 => self.r#type = SearchSettingsType::index_to_value(self.select_text_list.selected), 108 }
109 1 => {
110 self.date =
111 SearchSettingsDate::index_to_value(self.select_text_list.selected)
112 }
113 2 => {
114 self.duartion = SearchSettingsDuration::index_to_value(
115 self.select_text_list.selected,
116 )
117 }
118 3 => {
119 self.r#type =
120 SearchSettingsType::index_to_value(self.select_text_list.selected)
121 }
96 _ => {} 122 _ => {}
97 } 123 }
98 } 124 }
@@ -108,9 +134,9 @@ impl SearchSettings {
108 *self = Self::default(); 134 *self = Self::default();
109 self.text_list.selected = 4; 135 self.text_list.selected = 4;
110 self.update_left(); 136 self.update_left();
137 } else {
138 self.row = !self.row;
111 } 139 }
112
113 self.row = !self.row;
114 } 140 }
115 _ => {} 141 _ => {}
116 } 142 }
src/structs/watchhistory.rs +41 −20
@@ -7,9 +7,7 @@ use crate::app::config::Config;
7use super::ListItem; 7use super::ListItem;
8 8
9#[derive(Debug, Clone, Serialize, Deserialize)] 9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct WatchHistory(pub LinkedList<String>); 10pub struct WatchHistory(pub LinkedList<ListItem>);
11
12
13 11
14impl Default for WatchHistory { 12impl Default for WatchHistory {
15 fn default() -> Self { 13 fn default() -> Self {
@@ -38,11 +36,10 @@ impl WatchHistory {
38 36
39 pub fn push(&mut self, item: String, listitem: ListItem, config: &Config) { 37 pub fn push(&mut self, item: String, listitem: ListItem, config: &Config) {
40 if let Some(v) = self.0.front() { 38 if let Some(v) = self.0.front() {
41 if *v == item { 39 if *v.id() == item {
42 return; 40 return;
43 } 41 }
44 } 42 }
45 self.0.push_front(item);
46 43
47 let home_dir = home::home_dir().expect("Cannot get your home directory"); 44 let home_dir = home::home_dir().expect("Cannot get your home directory");
48 45
@@ -67,27 +64,51 @@ impl WatchHistory {
67 } 64 }
68 } 65 }
69 } 66 }
67
68 ListItem::FullPlayList(playlist) => {
69 let mut save_file = home_dir.join(".local/share/youtube-tui/watch_history/info");
70 save_file.push(format!("{}.json", playlist.playlist_id));
71 fs::write(save_file, serde_json::to_string(&listitem).unwrap()).unwrap();
72
73 let file_name = format!("{}.png", playlist.playlist_id);
74 original_dir.push(file_name.clone());
75
76 if original_dir.exists() {
77 let mut new_dir =
78 home_dir.join(".local/share/youtube-tui/watch_history/thumbnails");
79 new_dir.push(file_name);
80
81 if !new_dir.exists() {
82 fs::copy(original_dir, new_dir).expect("Cannot copy thumbnail");
83 }
84 }
85 }
70 _ => {} 86 _ => {}
71 } 87 }
72 88
89 self.0.push_front(listitem);
90
91 if self.0.len() > config.main.max_watch_history {
92 let back = self.0.pop_back();
93 if let Some(item) = back {
94 let id = item.id();
95 let _ = fs::remove_file(
96 home_dir
97 .join(".local/share/youtube-tui/watch_history/info")
98 .join(format!("{}.json", id.clone())),
99 );
100 let _ = fs::remove_file(
101 home_dir
102 .join(".local/share/youtube-tui/watch_history/thumbnails")
103 .join(format!("{}.png", id)),
104 );
105 }
106 }
107
73 fs::write( 108 fs::write(
74 home_dir.join(".local/share/youtube-tui/watch_history/watch_history.json"), 109 home_dir.join(".local/share/youtube-tui/watch_history/watch_history.json"),
75 serde_json::to_string(&self).unwrap(), 110 serde_json::to_string(&self).unwrap(),
76 ) 111 )
77 .expect("Cannot write watch history"); 112 .expect("Cannot write watch history");
78
79 if self.0.len() > config.main.max_watch_history {
80 let back = self.0.pop_back();
81 let _ = fs::remove_file(
82 home_dir
83 .join(".local/share/youtube-tui/watch_history/info")
84 .join(format!("{}.json", back.clone().unwrap())),
85 );
86 let _ = fs::remove_file(
87 home_dir
88 .join(".local/share/youtube-tui/watch_history/thumbnails")
89 .join(format!("{}.png", back.unwrap())),
90 );
91 }
92 } 113 }
93}\ No newline at end of file 114}
src/traits/load_item.rs deleted −7
@@ -1,7 +0,0 @@
1use std::error::Error;
2
3use crate::app::app::App;
4
5pub trait LoadItem {
6 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn Error>>;
7}
src/traits/mod.rs +1 −4
@@ -2,7 +2,4 @@ mod select_item;
2pub use select_item::*; 2pub use select_item::*;
3 3
4mod key_input; 4mod key_input;
5pub use key_input::*; 5pub use key_input::*;\ No newline at end of file
6
7mod load_item;
8pub use load_item::*;
src/widgets/item_display.rs +191 −14
@@ -1,8 +1,8 @@
1use tui::{ 1use tui::{
2 buffer::Buffer, 2 buffer::Buffer,
3 layout::Rect, 3 layout::{Alignment, Rect},
4 style::{Color, Style}, 4 style::{Color, Style},
5 widgets::Widget, 5 widgets::{Paragraph, Widget, Wrap},
6}; 6};
7use viuer::{print_from_file, Config}; 7use viuer::{print_from_file, Config};
8 8
@@ -55,18 +55,22 @@ impl Widget for ItemDisplay {
55 format!("Uploaded by {}", video.author), 55 format!("Uploaded by {}", video.author),
56 Style::default().fg(Color::LightGreen), 56 Style::default().fg(Color::LightGreen),
57 )); 57 ));
58 to_print.push(( 58 if let Some(s) = video.view_count {
59 format!("Views: {}", video.view_count), 59 to_print.push((
60 Style::default().fg(Color::LightYellow), 60 format!("Views: {}", s),
61 )); 61 Style::default().fg(Color::LightYellow),
62 ));
63 }
62 to_print.push(( 64 to_print.push((
63 format!("Length: {}", video.length), 65 format!("Length: {}", video.length),
64 Style::default().fg(Color::LightCyan), 66 Style::default().fg(Color::LightCyan),
65 )); 67 ));
66 to_print.push(( 68 if let Some(s) = video.published {
67 format!("Published {}", video.published), 69 to_print.push((
68 Style::default().fg(Color::LightMagenta), 70 format!("Published: {}", s),
69 )); 71 Style::default().fg(Color::LightMagenta),
72 ));
73 }
70 74
71 for (mut item, style) in to_print { 75 for (mut item, style) in to_print {
72 if y > area.height + area.y - 1 { 76 if y > area.height + area.y - 1 {
@@ -74,12 +78,19 @@ impl Widget for ItemDisplay {
74 } 78 }
75 79
76 if item.len() > area.width as usize { 80 if item.len() > area.width as usize {
77 item = format!("{}...", &item[..area.width as usize - 3]); 81 if item.len() > area.width as usize - 2 {
82 for _ in area.width as usize - 3..item.len() {
83 item.pop();
84 }
85
86 item.push('…');
87 }
78 } 88 }
79 buf.set_string(area.x, y, item, style); 89 buf.set_string(area.x, y, item, style);
80 y += 1; 90 y += 1;
81 } 91 }
82 } 92 }
93
83 ListItem::FullVideo(video) => { 94 ListItem::FullVideo(video) => {
84 let mut path = home::home_dir().expect("Cannot get your home directory"); 95 let mut path = home::home_dir().expect("Cannot get your home directory");
85 path.push(".cache"); 96 path.push(".cache");
@@ -115,8 +126,8 @@ impl Widget for ItemDisplay {
115 let mut to_print = Vec::new(); 126 let mut to_print = Vec::new();
116 let mut tags = Vec::new(); 127 let mut tags = Vec::new();
117 128
118 if video.nsfw { 129 if !video.nsfw {
119 tags.push("Non-Family Friendly"); 130 tags.push("Family Friendly");
120 } 131 }
121 132
122 if !video.public { 133 if !video.public {
@@ -158,6 +169,11 @@ impl Widget for ItemDisplay {
158 Style::default().fg(Color::LightMagenta), 169 Style::default().fg(Color::LightMagenta),
159 )); 170 ));
160 171
172 to_print.push((
173 String::from("Description: "),
174 Style::default().fg(Color::Gray),
175 ));
176
161 for (mut item, style) in to_print { 177 for (mut item, style) in to_print {
162 if y > area.height + area.y - 1 { 178 if y > area.height + area.y - 1 {
163 return; 179 return;
@@ -169,8 +185,169 @@ impl Widget for ItemDisplay {
169 buf.set_string(area.x, y, item, style); 185 buf.set_string(area.x, y, item, style);
170 y += 1; 186 y += 1;
171 } 187 }
188
189 if y < area.height + area.y {
190 let rect = Rect {
191 x: area.x,
192 y: y,
193 width: area.width,
194 height: area.height + area.y - y,
195 };
196
197 let paragraph = Paragraph::new(video.description.clone())
198 .wrap(Wrap { trim: true })
199 .alignment(Alignment::Left)
200 .style(Style::default().fg(Color::Gray));
201
202 paragraph.render(rect, buf);
203 }
204 }
205
206 ListItem::MiniPlayList(playlist) => {
207 let mut path = home::home_dir().expect("Cannot get your home directory");
208 path.push(".cache");
209 path.push("youtube-tui");
210 path.push("thumbnails");
211 path.push(format!("{}.png", playlist.playlist_id));
212 let exists = path.exists();
213 let mut image_transform = area;
214 if exists {
215 if image_transform.width * 9 > image_transform.height * 2 * 16 {
216 image_transform.width = image_transform.height * 2 * 16 / 9;
217 } else {
218 image_transform.height = image_transform.width * 9 / 32;
219 }
220
221 let conf = Config {
222 width: Some(image_transform.width as u32),
223 height: Some(image_transform.height as u32),
224 x: image_transform.x,
225 y: image_transform.y as i16,
226 ..Default::default()
227 };
228
229 let _ = print_from_file(path.as_os_str(), &conf);
230 }
231
232 let mut y = if exists {
233 image_transform.y + image_transform.height
234 } else {
235 area.y
236 };
237
238 let mut to_print = Vec::new();
239 to_print.push((String::from("[PlayList]"), Style::default().fg(Color::Gray)));
240 to_print.push((playlist.title, Style::default().fg(Color::LightBlue)));
241 to_print.push((
242 format!("Created by {}", playlist.author),
243 Style::default().fg(Color::LightGreen),
244 ));
245 to_print.push((
246 format!("Video Count: {}", playlist.video_count),
247 Style::default().fg(Color::LightCyan),
248 ));
249
250 for (mut item, style) in to_print {
251 if y > area.height + area.y - 1 {
252 return;
253 }
254
255 if item.len() > area.width as usize {
256 if item.len() > area.width as usize - 2 {
257 for _ in area.width as usize - 3..item.len() {
258 item.pop();
259 }
260
261 item.push('…');
262 }
263 }
264 buf.set_string(area.x, y, item, style);
265 y += 1;
266 }
267 }
268
269 ListItem::FullPlayList(playlist) => {
270 let mut path = home::home_dir().expect("Cannot get your home directory");
271 path.push(".cache");
272 path.push("youtube-tui");
273 path.push("thumbnails");
274 path.push(format!("{}.png", playlist.playlist_id));
275 let exists = path.exists();
276 let mut image_transform = area;
277 if exists {
278 if image_transform.width * 9 > image_transform.height * 2 * 16 {
279 image_transform.width = image_transform.height * 2 * 16 / 9;
280 } else {
281 image_transform.height = image_transform.width * 9 / 32;
282 }
283
284 let conf = Config {
285 width: Some(image_transform.width as u32),
286 height: Some(image_transform.height as u32),
287 x: image_transform.x,
288 y: image_transform.y as i16,
289 ..Default::default()
290 };
291
292 let _ = print_from_file(path.as_os_str(), &conf);
293 }
294
295 let mut y = if exists {
296 image_transform.y + image_transform.height
297 } else {
298 area.y
299 };
300
301 let mut to_print = Vec::new();
302 to_print.push((String::from("[PlayList]"), Style::default().fg(Color::Gray)));
303 to_print.push((playlist.title, Style::default().fg(Color::LightBlue)));
304 to_print.push((
305 format!("Created by {}", playlist.author),
306 Style::default().fg(Color::LightGreen),
307 ));
308 to_print.push((
309 format!("Video Count: {}", playlist.video_count),
310 Style::default().fg(Color::LightCyan),
311 ));
312 to_print.push((
313 format!("Views: {}", playlist.views),
314 Style::default().fg(Color::LightYellow),
315 ));
316
317 for (mut item, style) in to_print {
318 if y > area.height + area.y - 1 {
319 return;
320 }
321
322 if item.len() > area.width as usize {
323 if item.len() > area.width as usize - 2 {
324 for _ in area.width as usize - 3..item.len() {
325 item.pop();
326 }
327
328 item.push('…');
329 }
330 }
331
332 buf.set_string(area.x, y, item, style);
333
334 y += 1;
335 }
336 }
337
338 ListItem::PageTurner(b) => {
339 let paragraph = Paragraph::new(if b {
340 "Press enter to go to the next page"
341 } else {
342 "Press enter to go to the previous page"
343 })
344 .style(Style::default().bg(Color::DarkGray))
345 .wrap(Wrap { trim: true })
346 .alignment(Alignment::Center);
347
348 paragraph.render(area, buf);
172 } 349 }
173 _ => {} 350
174 } 351 }
175 } 352 }
176} 353}
src/widgets/text_list.rs +14 −9
@@ -38,10 +38,17 @@ impl Widget for TextList {
38 .skip(self.scroll) 38 .skip(self.scroll)
39 .take(area.height as usize - 2) 39 .take(area.height as usize - 2)
40 { 40 {
41 if item.len() > width_minus_2 { 41 let mut len = item.chars().count();
42 item = format!("{}...", &item[0..width_minus_5]); 42 if len > width_minus_2 {
43 for _ in width_minus_5..len {
44 item.pop();
45 }
46
47 item.push_str("...");
43 } 48 }
44 49
50 len = item.chars().count();
51
45 if i == self.selected { 52 if i == self.selected {
46 let horizontal = HORIZONTAL.to_string().repeat(width_minus_2); 53 let horizontal = HORIZONTAL.to_string().repeat(width_minus_2);
47 54
@@ -52,7 +59,7 @@ impl Widget for TextList {
52 ROUNDED_TOP_RIGHT, 59 ROUNDED_TOP_RIGHT,
53 VERTICAL, 60 VERTICAL,
54 item, 61 item,
55 " ".repeat(area.width as usize - 2 - item.len()), 62 " ".repeat(area.width as usize - 2 - len),
56 VERTICAL, 63 VERTICAL,
57 ROUNDED_BOTTOM_LEFT, 64 ROUNDED_BOTTOM_LEFT,
58 horizontal, 65 horizontal,
@@ -92,15 +99,13 @@ impl Widget for TextList {
92 buf.set_style(rect, self.selected_style); 99 buf.set_style(rect, self.selected_style);
93 100
94 for line in lines.lines() { 101 for line in lines.lines() {
95 for (x, c) in (0..area.width).zip(line.chars()) { 102 buf.set_string(area.x, y, line, Style::default());
96 buf.get_mut(area.x + x, y).set_char(c); 103
97 }
98 y += 1; 104 y += 1;
99 } 105 }
100 } else { 106 } else {
101 for (x, c) in (0..area.width).zip(item.chars()) { 107 buf.set_string(area.x + 1, y, item, Style::default());
102 buf.get_mut(area.x + x + 1, y).set_char(c); 108
103 }
104 y += 1; 109 y += 1;
105 } 110 }
106 } 111 }