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 = [
626626
627627[[package]]
628628name = "invidious"
629version = "0.2.0"
629version = "0.2.1"
630630source = "registry+https://github.com/rust-lang/crates.io-index"
631checksum = "89779909e071231edd52fae0a93b5c0a9b3d0d87f83fa0e4f2a958d8c9d66d0a"
631checksum = "b6d4c6a7a9048464b7265d607d7d94469143ae51bc76338a103f7d088c0e5da7"
632632dependencies = [
633633 "reqwest",
634634 "serde",
@@ -1716,7 +1716,7 @@ dependencies = [
17161716
17171717[[package]]
17181718name = "youtube-tui"
1719version = "0.1.0"
1719version = "0.2.0"
17201720dependencies = [
17211721 "chrono",
17221722 "crossterm",
Cargo.toml +1 −1
@@ -1,6 +1,6 @@
11[package]
22name = "youtube-tui"
3version = "0.1.0"
3version = "0.2.0"
44edition = "2021"
55authors = ["Siriusmart <siriusmart@tuta.io>"]
66description = "An aesthetically pleasing YouTube TUI written in Rust"
README.md +50 −6
@@ -3,20 +3,30 @@
33* This app is only for *\*nix* systems
44
55## 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)
78
89## Installation
910Requirements: Git, Cargo and the Rust Compiler
1011
12Executable size: ~12.5MB
13
1114```bash
15# Install from crates.io (might not be as up-to-date as the one on GitHub)
1216cargo install youtube-tui
1317```
1418
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
1524## Features
1625* View the Trending and Popular tab of YouTube
1726* View your Watch history
1827* Download videos and audio
1928* Watch videos and audio
29* Video and playlist support
2030
2131## Movement
2232* Use the arrow keys to move around the screen
@@ -37,7 +47,7 @@ cargo install youtube-tui
3747* Config files are stored in `~/.config/youtube-tui`
3848
3949## 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:
4151
4252> ### `main.yml`
4353> ```yaml
@@ -92,11 +102,45 @@ The config files are located in `~/.config/youtube-tui`, run the program once to
92102> args:
93103> - "-e"
94104> - "{command}"
95>
96
105> playlist_audio_all:
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> ```
97140## To Do
98* Search (For all items)
99* Adaptive config files (auto update when config files when there are new options in the config)
141* Channel support
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)
100144
101145## Bugs
102146* 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
17use serde::{Deserialize, Serialize};
28
39use crate::functions::insert_vec;
410
511use super::{Config, EnvVar};
612
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
728#[derive(Clone, Debug, Serialize, Deserialize)]
829pub struct CommandsConfig {
930 pub video_player: CommandConfig,
@@ -12,6 +33,11 @@ pub struct CommandsConfig {
1233 pub video_downloader: CommandConfig,
1334 pub audio_downloader: CommandConfig,
1435 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,
1541}
1642
1743#[derive(Clone, Debug, Serialize, Deserialize)]
@@ -113,6 +139,98 @@ impl Default for CommandsConfig {
113139 open_in_console: false,
114140 args: vec![String::from("-e"), String::from("{command}")],
115141 },
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;
116198 }
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)
117235 }
118236}
src/app/config/config.rs +5 −44
@@ -1,8 +1,4 @@
1use std::{
2 error::Error,
3 fs::{self, OpenOptions},
4 io::Write,
5};
1use std::error::Error;
62
73use super::{commands::CommandsConfig, MainConfig};
84
@@ -23,45 +19,10 @@ impl Default for Config {
2319
2420impl Config {
2521 pub fn load() -> Result<Self, Box<dyn Error>> {
26 let mut commands = CommandsConfig::default();
27 let mut main = MainConfig::default();
28
29 let mut config = home::home_dir().expect("Cannot get your home directory");
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 })
22 Ok(Self {
23 main: MainConfig::load()?,
24 commands: CommandsConfig::load()?,
25 })
6526 }
6627}
6728
src/app/config/main.rs +50
@@ -1,5 +1,13 @@
1use std::{error::Error, fs::{self, OpenOptions}, io::Write};
2
13use serde::{Deserialize, Serialize};
24
5#[derive(Clone, Debug, Serialize, Deserialize)]
6pub struct MainConfigTransitional {
7 pub yt_dl: Option<YtDlConfig>,
8 pub max_watch_history: Option<usize>,
9}
10
311#[derive(Clone, Debug, Serialize, Deserialize)]
412pub struct MainConfig {
513 pub yt_dl: YtDlConfig,
@@ -29,3 +37,45 @@ impl Default for YtDlConfig {
2937 }
3038 }
3139}
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::{
1212use crate::{
1313 app::app::App,
1414 functions::center_rect,
15 structs::{SearchSettings, Page},
15 structs::{Page, SearchSettings},
1616 traits::{KeyInput, SelectItem},
1717 widgets::{force_clear::ForceClear, horizontal_split::HorizontalSplit},
1818};
@@ -83,25 +83,30 @@ impl KeyInput for GlobalItem {
8383 app.search_text.pop();
8484 }
8585 KeyCode::Enter => {
86 let state = Search::default();
87 let mut history = app.history.clone();
88 let search_text = app.search_text.clone();
89 let search_settings = app.search_settings.clone();
90 history.push(app.into());
91
92 return (
93 false,
94 App {
95 history,
96 page: Page::Search,
97 selectable: App::selectable(&state),
98 state,
99 search_text,
100 search_settings,
101 load: true,
102 ..Default::default()
103 },
104 );
86 if app.search_text.len() == 0 {
87 *app.message.lock().unwrap() =
88 Some(String::from("Search term cannot be empty"));
89 } else {
90 let state = Search::default();
91 let mut history = app.history.clone();
92 let search_text = app.search_text.clone();
93 let search_settings = app.search_settings.clone();
94 history.push(app.into());
95
96 return (
97 false,
98 App {
99 history,
100 page: Page::Search,
101 selectable: App::selectable(&state),
102 state,
103 search_text,
104 search_settings,
105 load: true,
106 ..Default::default()
107 },
108 );
109 }
105110 }
106111 _ => {}
107112 },
src/app/pages/item_info.rs +453 −38
@@ -1,5 +1,6 @@
11use std::{
22 collections::LinkedList,
3 error::Error,
34 process::Command,
45 sync::{Arc, Mutex},
56 thread,
@@ -8,8 +9,8 @@ use std::{
89use crate::{
910 app::{app::App, config::EnvVar, pages::global::*},
1011 functions::download_all_thumbnails,
11 structs::{FullVideo, Item, ListItem, Page, Row, RowItem},
12 traits::{KeyInput, LoadItem, SelectItem},
12 structs::{FullPlayList, FullVideo, Item, ListItem, Page, Row, RowItem, WatchHistory},
13 traits::{KeyInput, SelectItem},
1314 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
1415};
1516use crossterm::event::KeyCode;
@@ -26,6 +27,7 @@ use super::global::GlobalItem;
2627pub enum ItemInfoItem {
2728 Unknown,
2829 Video(VideoItemInfo),
30 PlayList(PlayListItemInfo),
2931}
3032
3133#[derive(Debug, Clone)]
@@ -35,6 +37,30 @@ pub struct VideoItemInfo {
3537 mode: Mode,
3638}
3739
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
3864impl SelectItem for ItemInfoItem {
3965 fn select(&mut self, app: App) -> (App, bool) {
4066 let selected = true;
@@ -48,7 +74,7 @@ impl SelectItem for ItemInfoItem {
4874}
4975
5076impl 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) {
5278 match self {
5379 ItemInfoItem::Video(videoinfo) => match key {
5480 KeyCode::Up => videoinfo.list.up(),
@@ -62,11 +88,6 @@ impl KeyInput for ItemInfoItem {
6288
6389 match videoinfo.list.selected {
6490 0 => {
65 app.watch_history.push(
66 videoinfo.video.video_id.clone(),
67 ListItem::FullVideo(videoinfo.video.clone()),
68 &app.config,
69 );
7091 let command =
7192 match app.config.commands.video_player.clone().as_command_vec(
7293 EnvVar {
@@ -99,11 +120,6 @@ impl KeyInput for ItemInfoItem {
99120 run_command(command, app.message.clone());
100121 }
101122 1 => {
102 app.watch_history.push(
103 videoinfo.video.video_id.clone(),
104 ListItem::FullVideo(videoinfo.video.clone()),
105 &app.config,
106 );
107123 let command =
108124 match app.config.commands.audio_player.clone().as_command_vec(
109125 EnvVar {
@@ -136,11 +152,6 @@ impl KeyInput for ItemInfoItem {
136152 run_command(command, app.message.clone());
137153 }
138154 2 => {
139 app.watch_history.push(
140 videoinfo.video.video_id.clone(),
141 ListItem::FullVideo(videoinfo.video.clone()),
142 &app.config,
143 );
144155 let command =
145156 match app.config.commands.video_downloader.clone().as_command_vec(
146157 EnvVar {
@@ -173,11 +184,6 @@ impl KeyInput for ItemInfoItem {
173184 run_command(command, app.message.clone());
174185 }
175186 3 => {
176 app.watch_history.push(
177 videoinfo.video.video_id.clone(),
178 ListItem::FullVideo(videoinfo.video.clone()),
179 &app.config,
180 );
181187 let command =
182188 match app.config.commands.audio_downloader.clone().as_command_vec(
183189 EnvVar {
@@ -216,11 +222,6 @@ impl KeyInput for ItemInfoItem {
216222 dir.push("youtube-tui");
217223 dir.push("thumbnails");
218224 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 // ];
224225
225226 let command =
226227 match app.config.commands.image_viewer.clone().as_command_vec(
@@ -254,6 +255,301 @@ impl KeyInput for ItemInfoItem {
254255 }
255256 _ => {}
256257 },
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 },
257553 _ => {}
258554 }
259555
@@ -261,8 +557,12 @@ impl KeyInput for ItemInfoItem {
261557 }
262558}
263559
264impl LoadItem for ItemInfoItem {
265 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn std::error::Error>> {
560impl ItemInfoItem {
561 pub fn load_item(
562 &self,
563 app: &App,
564 watch_history: &mut WatchHistory,
565 ) -> Result<Box<Self>, Box<dyn Error>> {
266566 let mut this = self.clone();
267567
268568 if let ItemInfoItem::Unknown = this {
@@ -284,11 +584,66 @@ impl LoadItem for ItemInfoItem {
284584 String::from("Visit channel"),
285585 String::from("Mode placeholder"),
286586 ]);
287 this = ItemInfoItem::Video(VideoItemInfo {
587
588 let iteminfo = VideoItemInfo {
288589 video,
289590 list,
290591 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);
292647 }
293648 },
294649
@@ -297,9 +652,7 @@ impl LoadItem for ItemInfoItem {
297652 }
298653 Ok(Box::new(this))
299654 }
300}
301655
302impl ItemInfoItem {
303656 pub fn render_item<B: Backend>(
304657 &mut self,
305658 frame: &mut Frame<B>,
@@ -347,6 +700,60 @@ impl ItemInfoItem {
347700 frame.render_widget(list, chunks[1]);
348701 }
349702
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
350757 ItemInfoItem::Unknown => {
351758 let split = HorizontalSplit::default()
352759 .percentages(vec![40, 60])
@@ -357,6 +764,7 @@ impl ItemInfoItem {
357764 } else {
358765 Color::Reset
359766 }));
767
360768 frame.render_widget(split, rect);
361769 }
362770 }
@@ -366,6 +774,7 @@ impl ItemInfoItem {
366774#[derive(Debug, Clone, PartialEq)]
367775pub enum DisplayItem {
368776 Video(String),
777 PlayList(String),
369778}
370779
371780pub struct ItemInfo;
@@ -382,10 +791,16 @@ impl ItemInfo {
382791 pub fn default() -> Vec<Row> {
383792 vec![
384793 Row {
385 items: vec![RowItem {
386 item: Item::Global(GlobalItem::SearchBar),
387 constraint: Constraint::Percentage(100),
388 }],
794 items: vec![
795 RowItem {
796 item: Item::Global(GlobalItem::SearchBar),
797 constraint: Constraint::Min(16),
798 },
799 RowItem {
800 item: Item::Global(GlobalItem::SearchSettings),
801 constraint: Constraint::Length(5),
802 },
803 ],
389804 centered: false,
390805 height: Constraint::Length(3),
391806 },
src/app/pages/main_menu.rs +36 −16
@@ -7,7 +7,7 @@ use crate::{
77 },
88 functions::download_all_thumbnails,
99 structs::{Item, ListItem, Page, Row, RowItem},
10 traits::{KeyInput, LoadItem, SelectItem},
10 traits::{KeyInput, SelectItem},
1111 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
1212};
1313use crossterm::event::KeyCode;
@@ -52,11 +52,11 @@ impl SelectItem for MainMenuItem {
5252impl KeyInput for MainMenuItem {
5353 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
5454 match self {
55 MainMenuItem::VideoList(Some((video_list, list, _))) => match key {
56 KeyCode::Up => list.up(),
57 KeyCode::Down => list.down(),
58 KeyCode::PageUp => list.selected = 0,
59 KeyCode::PageDown => list.selected = list.items.len() - 1,
55 MainMenuItem::VideoList(Some((list, textlist, _))) => match key {
56 KeyCode::Up => textlist.up(),
57 KeyCode::Down => textlist.down(),
58 KeyCode::PageUp => textlist.selected = 0,
59 KeyCode::PageDown => textlist.selected = textlist.items.len() - 1,
6060 KeyCode::Enter => {
6161 let state = ItemInfo::default();
6262 let mut history = app.history.clone();
@@ -66,9 +66,31 @@ impl KeyInput for MainMenuItem {
6666 false,
6767 App {
6868 history,
69 page: Page::ItemDisplay(DisplayItem::Video(
70 video_list.iter().nth(list.selected).unwrap().id(),
71 )),
69 page: Page::ItemDisplay(
70 match list.iter().nth(textlist.selected).unwrap() {
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 ),
7294 selectable: App::selectable(&state),
7395 state,
7496 ..Default::default()
@@ -84,8 +106,8 @@ impl KeyInput for MainMenuItem {
84106 }
85107}
86108
87impl LoadItem for MainMenuItem {
88 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn Error>> {
109impl MainMenuItem {
110 pub fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn Error>> {
89111 let mut this = self.clone();
90112
91113 match &mut this {
@@ -132,7 +154,7 @@ impl LoadItem for MainMenuItem {
132154 .map(|t| ListItem::MiniVideo(t.into()))
133155 .collect();
134156
135 download_all_thumbnails(
157 let _ = download_all_thumbnails(
136158 list.iter()
137159 .map(|t| match t {
138160 ListItem::MiniVideo(v) => {
@@ -141,7 +163,7 @@ impl LoadItem for MainMenuItem {
141163 _ => unreachable!(),
142164 })
143165 .collect(),
144 )?;
166 );
145167
146168 let mut text_list = TextList::default();
147169
@@ -165,7 +187,7 @@ impl LoadItem for MainMenuItem {
165187 home::home_dir()
166188 .expect("Cannot get your home directory")
167189 .join(".local/share/youtube-tui/watch_history/info")
168 .join(format!("{}.json", t)),
190 .join(format!("{}.json", t.id())),
169191 );
170192
171193 if let Ok(file) = file {
@@ -189,9 +211,7 @@ impl LoadItem for MainMenuItem {
189211
190212 Ok(Box::new(this))
191213 }
192}
193214
194impl MainMenuItem {
195215 pub fn render_item<B: Backend>(
196216 &mut self,
197217 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};
22
33use crossterm::event::KeyCode;
44use invidious::structs::hidden::SearchItem as InvidiousSearchItem;
@@ -12,8 +12,8 @@ use tui::{
1212use crate::{
1313 app::app::App,
1414 functions::download_all_thumbnails,
15 structs::{Item, ListItem, MiniVideo, Page, Row, RowItem},
16 traits::{KeyInput, LoadItem, SelectItem},
15 structs::{Item, ListItem, MiniPlayList, MiniVideo, Page, Row, RowItem},
16 traits::{KeyInput, SelectItem},
1717 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
1818};
1919
@@ -104,6 +104,25 @@ impl KeyInput for SearchItem {
104104 );
105105 }
106106
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
107126 _ => {}
108127 }
109128 }
@@ -116,99 +135,110 @@ impl KeyInput for SearchItem {
116135 }
117136}
118137
119impl LoadItem for SearchItem {
120 fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn std::error::Error>> {
138impl SearchItem {
139 pub fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn Error>> {
121140 let mut this = self.clone();
122141
123142 match &mut this {
124143 SearchItem::Search { results, text_list } => {
125144 // 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 }
165145
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)));
167180 }
168 }
169181
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 }
171193
172 if app.page_no != 1 {
173 minimum_length += 1;
174 items.push_front(ListItem::PageTurner(false));
194 _ => {}
175195 }
196 }
176197
177 if items.len() == minimum_length {
178 *app.message.lock().unwrap() = Some(String::from("No results found"));
179 } else {
180 items.push_back(ListItem::PageTurner(true));
181 }
198 let mut minimum_length = 0;
182199
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 }
184204
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 }
186210
187 for item in items.iter() {
188 match item {
189 ListItem::MiniVideo(video) => {
190 thumbnails.push_back((
191 video.video_thumbnail.clone(),
192 video.video_id.clone(),
193 ));
194 }
211 text_list.items = textlist_from_video_list(&items);
195212
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()));
197220 }
198 }
199221
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 }
201228
202 *results = Some(items);
229 _ => {}
230 }
203231 }
232
233 let _ = download_all_thumbnails(thumbnails);
234
235 *results = Some(items);
204236 }
205237 }
206238
207239 Ok(Box::new(this))
208240 }
209}
210241
211impl SearchItem {
212242 pub fn render_item<B: Backend>(
213243 &mut self,
214244 frame: &mut Frame<B>,
@@ -217,7 +247,6 @@ impl SearchItem {
217247 hover: bool,
218248 popup_focus: bool,
219249 ) {
220
221250 match self {
222251 SearchItem::Search { results, text_list } => {
223252 let split = HorizontalSplit::default()
src/functions/download_all_thumbnails.rs +1 −1
@@ -5,7 +5,7 @@ use tokio::runtime::Runtime;
55
66pub enum ItemType {
77 Video,
8 Playlist,
8 PlayList,
99}
1010
1111pub fn download_all_thumbnails(
src/main.rs +18 −16
@@ -14,7 +14,6 @@ use youtube_tui::{
1414 pages::{item_info::ItemInfo, main_menu::MainMenu, search::Search},
1515 },
1616 structs::{Item, Page, Row, RowItem},
17 traits::LoadItem,
1817};
1918
2019fn main() -> Result<(), Box<dyn Error>> {
@@ -77,21 +76,25 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
7776 *app.message.lock().unwrap() = Some(e.to_string());
7877 }
7978 },
80 Item::ItemInfo(item) => match item.load_item(&app) {
81 Ok(new) => {
82 row_vec.push(RowItem {
83 item: Item::ItemInfo(*new),
84 ..*row_item
85 });
86 }
87 Err(e) => {
88 row_vec.push(RowItem {
89 item: Item::ItemInfo(item.clone()),
90 ..*row_item
91 });
92 *app.message.lock().unwrap() = Some(e.to_string());
79 Item::ItemInfo(item) => {
80 let mut watch_history = app.watch_history.clone();
81 match item.load_item(&app, &mut watch_history) {
82 Ok(new) => {
83 row_vec.push(RowItem {
84 item: Item::ItemInfo(*new),
85 ..*row_item
86 });
87 }
88 Err(e) => {
89 row_vec.push(RowItem {
90 item: Item::ItemInfo(item.clone()),
91 ..*row_item
92 });
93 *app.message.lock().unwrap() = Some(e.to_string());
94 }
9395 }
94 },
96 app.watch_history = watch_history;
97 }
9598 Item::Search(item) => match item.load_item(&app) {
9699 Ok(new) => {
97100 row_vec.push(RowItem {
@@ -255,7 +258,6 @@ fn init() -> Result<(), Box<dyn Error>> {
255258 fs::create_dir(&dir)?;
256259 }
257260
258
259261 Ok(())
260262}
261263
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 @@
11use crate::structs::{FullVideo, MiniVideo};
22use serde::{Deserialize, Serialize};
33
4use super::{FullPlayList, MiniPlayList};
5
46#[derive(Debug, Clone, Deserialize, Serialize)]
57pub enum ListItem {
68 MiniVideo(MiniVideo),
79 FullVideo(FullVideo),
10 MiniPlayList(MiniPlayList),
11 FullPlayList(FullPlayList),
812 PageTurner(bool), // true: +1 | false: -1
913}
1014
@@ -13,6 +17,8 @@ impl ListItem {
1317 match self {
1418 ListItem::MiniVideo(video) => video.video_id.clone(),
1519 ListItem::FullVideo(video) => video.video_id.clone(),
20 ListItem::MiniPlayList(playlist) => playlist.playlist_id.clone(),
21 ListItem::FullPlayList(playlist) => playlist.playlist_id.clone(),
1622 _ => {
1723 unreachable!()
1824 }
@@ -40,6 +46,18 @@ impl ListItem {
4046 .into_iter()
4147 .filter(|c| !c.is_ascii_control())
4248 .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(),
4361 ListItem::PageTurner(turner) => {
4462 if *turner {
4563 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 @@
11use chrono::{prelude::*, Utc};
2use invidious::structs::hidden::{PopularItem, TrendingVideo, SearchItem};
2use invidious::structs::hidden::{PopularItem, TrendingVideo, SearchItem, PlaylistItem};
33use thousands::Separable;
44use serde::{Deserialize, Serialize};
55
@@ -9,11 +9,11 @@ pub struct MiniVideo {
99 pub video_id: String,
1010 pub video_thumbnail: String,
1111 pub length: String,
12 pub view_count: String,
12 pub view_count: Option<String>,
1313 pub author: String,
1414 pub author_url: String,
15 pub published: String,
16 pub description: String,
15 pub published: Option<String>,
16 pub description: Option<String>,
1717}
1818
1919impl From<TrendingVideo> for MiniVideo {
@@ -23,10 +23,10 @@ impl From<TrendingVideo> for MiniVideo {
2323 video_id: original.videoId,
2424 video_thumbnail: original.videoThumbnails[4].url.clone(),
2525 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()),
2727 author: original.author,
2828 author_url: original.authorUrl,
29 published: format!(
29 published: Some(format!(
3030 "{}{}",
3131 original.publishedText,
3232 if Utc::now().timestamp() - original.published as i64 > 86400 {
@@ -38,8 +38,8 @@ impl From<TrendingVideo> for MiniVideo {
3838 } else {
3939 String::new()
4040 }
41 ),
42 description: original.description,
41 )),
42 description: Some(original.description),
4343 }
4444 }
4545}
@@ -51,10 +51,10 @@ impl From<PopularItem> for MiniVideo {
5151 video_id: original.videoId,
5252 video_thumbnail: original.videoThumbnails[5].url.clone(),
5353 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()),
5555 author: original.author,
5656 author_url: original.authorUrl,
57 published: format!(
57 published: Some(format!(
5858 "{}{}",
5959 original.publishedText,
6060 if Utc::now().timestamp() - original.published as i64 > 86400 {
@@ -66,8 +66,8 @@ impl From<PopularItem> for MiniVideo {
6666 } else {
6767 String::new()
6868 }
69 ),
70 description: String::new(),
69 )),
70 description: None,
7171 }
7272 }
7373}
@@ -81,10 +81,10 @@ impl From<SearchItem> for MiniVideo {
8181 video_id: videoId,
8282 video_thumbnail: videoThumbnails[0].url.clone(),
8383 length: hrtime::from_sec_padded(lengthSeconds as u64),
84 view_count: viewCount.separate_with_commas(),
84 view_count: Some(viewCount.separate_with_commas()),
8585 author: author,
8686 author_url: authorUrl,
87 published: format!(
87 published: Some(format!(
8888 "{}{}",
8989 publishedText,
9090 if Utc::now().timestamp() - published as i64 > 86400 {
@@ -96,12 +96,29 @@ impl From<SearchItem> for MiniVideo {
9696 } else {
9797 String::new()
9898 }
99 ),
100 description: description,
99 )),
100 description: Some(description),
101101 }
102102 }
103103
104104 _ => unreachable!(),
105105 }
106106 }
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 }
107124}
\ No newline at end of file
src/structs/mod.rs +7 −1
@@ -20,4 +20,10 @@ mod watchhistory;
2020pub use watchhistory::*;
2121
2222mod 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 {
7373 self.select_text_list.up();
7474
7575 match self.text_list.selected {
76 0 => self.sort_by = SearchSettingsSortBy::index_to_value(self.select_text_list.selected),
77 1 => self.date = SearchSettingsDate::index_to_value(self.select_text_list.selected),
78 2 => self.duartion = SearchSettingsDuration::index_to_value(self.select_text_list.selected),
79 3 => self.r#type = SearchSettingsType::index_to_value(self.select_text_list.selected),
76 0 => {
77 self.sort_by =
78 SearchSettingsSortBy::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 }
8093 _ => {}
8194 }
8295 }
@@ -89,10 +102,23 @@ impl SearchSettings {
89102 self.select_text_list.down();
90103
91104 match self.text_list.selected {
92 0 => self.sort_by = SearchSettingsSortBy::index_to_value(self.select_text_list.selected),
93 1 => self.date = SearchSettingsDate::index_to_value(self.select_text_list.selected),
94 2 => self.duartion = SearchSettingsDuration::index_to_value(self.select_text_list.selected),
95 3 => self.r#type = SearchSettingsType::index_to_value(self.select_text_list.selected),
105 0 => {
106 self.sort_by =
107 SearchSettingsSortBy::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 }
96122 _ => {}
97123 }
98124 }
@@ -108,9 +134,9 @@ impl SearchSettings {
108134 *self = Self::default();
109135 self.text_list.selected = 4;
110136 self.update_left();
137 } else {
138 self.row = !self.row;
111139 }
112
113 self.row = !self.row;
114140 }
115141 _ => {}
116142 }
src/structs/watchhistory.rs +41 −20
@@ -7,9 +7,7 @@ use crate::app::config::Config;
77use super::ListItem;
88
99#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct WatchHistory(pub LinkedList<String>);
11
12
10pub struct WatchHistory(pub LinkedList<ListItem>);
1311
1412impl Default for WatchHistory {
1513 fn default() -> Self {
@@ -38,11 +36,10 @@ impl WatchHistory {
3836
3937 pub fn push(&mut self, item: String, listitem: ListItem, config: &Config) {
4038 if let Some(v) = self.0.front() {
41 if *v == item {
39 if *v.id() == item {
4240 return;
4341 }
4442 }
45 self.0.push_front(item);
4643
4744 let home_dir = home::home_dir().expect("Cannot get your home directory");
4845
@@ -67,27 +64,51 @@ impl WatchHistory {
6764 }
6865 }
6966 }
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 }
7086 _ => {}
7187 }
7288
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
73108 fs::write(
74109 home_dir.join(".local/share/youtube-tui/watch_history/watch_history.json"),
75110 serde_json::to_string(&self).unwrap(),
76111 )
77112 .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 }
92113 }
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;
22pub use select_item::*;
33
44mod key_input;
5pub use key_input::*;
6
7mod load_item;
8pub use load_item::*;
5pub use key_input::*;
\ No newline at end of file
src/widgets/item_display.rs +191 −14
@@ -1,8 +1,8 @@
11use tui::{
22 buffer::Buffer,
3 layout::Rect,
3 layout::{Alignment, Rect},
44 style::{Color, Style},
5 widgets::Widget,
5 widgets::{Paragraph, Widget, Wrap},
66};
77use viuer::{print_from_file, Config};
88
@@ -55,18 +55,22 @@ impl Widget for ItemDisplay {
5555 format!("Uploaded by {}", video.author),
5656 Style::default().fg(Color::LightGreen),
5757 ));
58 to_print.push((
59 format!("Views: {}", video.view_count),
60 Style::default().fg(Color::LightYellow),
61 ));
58 if let Some(s) = video.view_count {
59 to_print.push((
60 format!("Views: {}", s),
61 Style::default().fg(Color::LightYellow),
62 ));
63 }
6264 to_print.push((
6365 format!("Length: {}", video.length),
6466 Style::default().fg(Color::LightCyan),
6567 ));
66 to_print.push((
67 format!("Published {}", video.published),
68 Style::default().fg(Color::LightMagenta),
69 ));
68 if let Some(s) = video.published {
69 to_print.push((
70 format!("Published: {}", s),
71 Style::default().fg(Color::LightMagenta),
72 ));
73 }
7074
7175 for (mut item, style) in to_print {
7276 if y > area.height + area.y - 1 {
@@ -74,12 +78,19 @@ impl Widget for ItemDisplay {
7478 }
7579
7680 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 }
7888 }
7989 buf.set_string(area.x, y, item, style);
8090 y += 1;
8191 }
8292 }
93
8394 ListItem::FullVideo(video) => {
8495 let mut path = home::home_dir().expect("Cannot get your home directory");
8596 path.push(".cache");
@@ -115,8 +126,8 @@ impl Widget for ItemDisplay {
115126 let mut to_print = Vec::new();
116127 let mut tags = Vec::new();
117128
118 if video.nsfw {
119 tags.push("Non-Family Friendly");
129 if !video.nsfw {
130 tags.push("Family Friendly");
120131 }
121132
122133 if !video.public {
@@ -158,6 +169,11 @@ impl Widget for ItemDisplay {
158169 Style::default().fg(Color::LightMagenta),
159170 ));
160171
172 to_print.push((
173 String::from("Description: "),
174 Style::default().fg(Color::Gray),
175 ));
176
161177 for (mut item, style) in to_print {
162178 if y > area.height + area.y - 1 {
163179 return;
@@ -169,8 +185,169 @@ impl Widget for ItemDisplay {
169185 buf.set_string(area.x, y, item, style);
170186 y += 1;
171187 }
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);
172349 }
173 _ => {}
350
174351 }
175352 }
176353}
src/widgets/text_list.rs +14 −9
@@ -38,10 +38,17 @@ impl Widget for TextList {
3838 .skip(self.scroll)
3939 .take(area.height as usize - 2)
4040 {
41 if item.len() > width_minus_2 {
42 item = format!("{}...", &item[0..width_minus_5]);
41 let mut len = item.chars().count();
42 if len > width_minus_2 {
43 for _ in width_minus_5..len {
44 item.pop();
45 }
46
47 item.push_str("...");
4348 }
4449
50 len = item.chars().count();
51
4552 if i == self.selected {
4653 let horizontal = HORIZONTAL.to_string().repeat(width_minus_2);
4754
@@ -52,7 +59,7 @@ impl Widget for TextList {
5259 ROUNDED_TOP_RIGHT,
5360 VERTICAL,
5461 item,
55 " ".repeat(area.width as usize - 2 - item.len()),
62 " ".repeat(area.width as usize - 2 - len),
5663 VERTICAL,
5764 ROUNDED_BOTTOM_LEFT,
5865 horizontal,
@@ -92,15 +99,13 @@ impl Widget for TextList {
9299 buf.set_style(rect, self.selected_style);
93100
94101 for line in lines.lines() {
95 for (x, c) in (0..area.width).zip(line.chars()) {
96 buf.get_mut(area.x + x, y).set_char(c);
97 }
102 buf.set_string(area.x, y, line, Style::default());
103
98104 y += 1;
99105 }
100106 } else {
101 for (x, c) in (0..area.width).zip(item.chars()) {
102 buf.get_mut(area.x + x + 1, y).set_char(c);
103 }
107 buf.set_string(area.x + 1, y, item, Style::default());
108
104109 y += 1;
105110 }
106111 }