Commit 2a2a2fa4a5

2a2a2fa4a5238515d8e2b21c975824c74f72606c

parent: 641938ba1f

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-05-21 17:17 UTC

Config files and watch history

Layout: unified · split

Cargo.lock +30
@@ -683,6 +683,12 @@ version = "0.2.124"
683683source = "registry+https://github.com/rust-lang/crates.io-index"
684684checksum = "21a41fed9d98f27ab1c6d161da622a4fa35e8a54a8adc24bbf3ddd0ef70b0e50"
685685
686[[package]]
687name = "linked-hash-map"
688version = "0.5.4"
689source = "registry+https://github.com/rust-lang/crates.io-index"
690checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
691
686692[[package]]
687693name = "lock_api"
688694version = "0.4.7"
@@ -1165,6 +1171,18 @@ dependencies = [
11651171 "serde",
11661172]
11671173
1174[[package]]
1175name = "serde_yaml"
1176version = "0.8.24"
1177source = "registry+https://github.com/rust-lang/crates.io-index"
1178checksum = "707d15895415db6628332b737c838b88c598522e4dc70647e59b72312924aebc"
1179dependencies = [
1180 "indexmap",
1181 "ryu",
1182 "serde",
1183 "yaml-rust",
1184]
1185
11681186[[package]]
11691187name = "signal-hook"
11701188version = "0.3.13"
@@ -1687,6 +1705,15 @@ dependencies = [
16871705 "winapi",
16881706]
16891707
1708[[package]]
1709name = "yaml-rust"
1710version = "0.4.5"
1711source = "registry+https://github.com/rust-lang/crates.io-index"
1712checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
1713dependencies = [
1714 "linked-hash-map",
1715]
1716
16901717[[package]]
16911718name = "youtube-tui"
16921719version = "0.1.0"
@@ -1698,6 +1725,9 @@ dependencies = [
16981725 "hrtime",
16991726 "invidious",
17001727 "reqwest",
1728 "serde",
1729 "serde_json",
1730 "serde_yaml",
17011731 "thousands",
17021732 "tokio",
17031733 "tui",
Cargo.toml +3
@@ -17,6 +17,9 @@ tokio = { version = "1.18", features = ["full"] }
1717viuer = "0.6"
1818thousands = "0.2"
1919chrono = "0.4"
20serde = "1"
21serde_yaml = "0.8"
22serde_json = "1"
2023
2124[profile.dev.package."*"]
2225opt-level = 3
README.md +96 −36
@@ -1,41 +1,101 @@
1## Warning: This program is made for Linux machines (And maybe MacOS?)
2
13## Changes made in this commit
2* Home page button
3* Video/audio playing and downloading - can play from YouTube (recommended) or invidious server (Bro you are killing their bandwidth)
4* Still lacking a lot of main features, but it is now a functional program (check the popular tab those videos are more relevant)
5
6## Requirements
7(These requirements will be removed in the next commit as it will *hopefully* allows you to choose the software/commands you want to use)
8* yt-dlp (for downloading videos/audio)
9* mpv (for video/audio playing and thumbnail preview)
10* konsole (for opening the terminal when downloading and playing audio)
11
12## What Will (Hopefully) Be in the Next Commit
13* Config files
14* Watch history
15
16## Basic Movements
17> Arrow keys: Move in the direction of the arrow key.
18>
19> Enter: Select an item (Everything is an item)
20>
21> Esc: Unselect an item
22>
23> q: Quit the program (Only works when nothing is selected)
24>
25> Backspace: Go back in history
26>
27> End: Clear history
28>
29> Home: Go to homepage
4* Watch history page
5* Config files in `~/.config/youtube-tui`
306
31## Basic Display
32> Green (Or your terminal's default foreground color): All the items
33>
34> Red: The item that you have your "cursor" on (Aka hovering)
35>
36> Blue/Purple: The item that you have selected
7## Installation
8Requirements: Git, Cargo and the Rust Compiler
9
10```bash
11git clone https://github.com/Siriusmart/youtube-tui && cd youtube-tui && cargo build
12```
13
14## Features
15* View the Trending and Popular tab of YouTube
16* View your Watch history
17* Download videos and audio
18* Watch videos and audio
19
20## Movement
21* Use the arrow keys to move around the screen
22* Press enter to select an item
23* When item is selected all your keys will be passed into it
24* Press escape to exit the item
25* Press q to quit the program
26
27## Layout
28* Each divided area is one item
29* Red shows the item your currently on
30* Blue shows the selected item
31* Yellow shows an item in a special state
32
33## Storage
34* Cache is stored in `~/.cache/youtube-tui`, it is cleared when you quit the program
35* Storage is stored in `~/.local/share/youtube-tui`
36* Config files are stored in `~/.config/youtube-tui`
37
38## Config files
39The config files are located in `~/.config/youtube-tui`, run the program once to create the config files.
40
41> ### `main.yml`
42> ```yaml
43> # The program's main config file
44> ---
45> yt_dl: # Donwload location for your downloaded videos
46> video_path: ~/Downloads/%(title)s.%(ext)s
47> audio_path: ~/Downloads/%(title)s.%(ext)s
48> max_watch_history: 50 # Maximum length of watch history
49> ```
50
51> ### `commands.yml`
52> ```yaml
53> # Command arguments to use when launching applications
54> ---
55> video_player:
56> command: mpv
57> open_in_console: false
58> args:
59> - "--no-terminal"
60> - "{url}"
61> audio_player:
62> command: mpv
63> open_in_console: true
64> args:
65> - "--no-video"
66> - "{url}"
67> image_viewer:
68> command: mpv
69> open_in_console: false
70> args:
71> - "{url}"
72> - "--no-terminal"
73> video_downloader:
74> command: yt-dlp
75> open_in_console: true
76> args:
77> - "{url}"
78> - "-o"
79> - "{video_save_location}"
80> audio_downloader:
81> command: yt-dlp
82> open_in_console: true
83> args:
84> - "{url}"
85> - "-o"
86> - "{audio_save_location}"
87> - "-x"
88> terminal:
89> command: konsole
90> open_in_console: false
91> args:
92> - "-e"
93> - "{command}"
3794>
38> Yellow: Selected but not selected? (I don't know how to say that)
95
96## To Do
97* Make the search bar functional
98* View channels
3999
40100## Bugs
41> NONE! It's just a feature. If you found one, please report the feature you've just discovered on GitHub
\ No newline at end of file
101* If there is a bug please open a GitHub issue thx :)
\ No newline at end of file
file.txt deleted −5
@@ -1,5 +0,0 @@
1ItemDisplay(Video("GjMmsEwIcl0"))
2ItemDisplay(Video("V2kWUJkRvVs"))
3ItemDisplay(Video("_CH8uu3L4D0"))
4ItemDisplay(Video("bLxbHQolYCo"))
5ItemDisplay(Video("8meLVxHw5nM"))
src/app/app.rs +28 −10
@@ -1,10 +1,14 @@
1use std::{collections::LinkedList, sync::{Arc, Mutex}};
1use std::{
2 collections::LinkedList,
3 sync::{Arc, Mutex},
4};
25
36use crate::{
4 app::pages::{main_menu::*},
5 traits::{KeyInput, SelectItem}, structs::{AppHistory, Item, Page, Row},
7 app::pages::main_menu::*,
8 structs::{AppHistory, Item, Page, Row, WatchHistory},
9 traits::{KeyInput, SelectItem},
610};
7use crossterm::{event::KeyCode};
11use crossterm::event::KeyCode;
812use invidious::blocking::Client;
913use tui::{
1014 backend::Backend,
@@ -14,8 +18,11 @@ use tui::{
1418 Frame,
1519};
1620
21use super::config::Config;
22
1723#[derive(Debug)]
1824pub struct App {
25 pub config: Config,
1926 pub page: Page,
2027 pub state: Vec<Row>, // Item
2128 pub selectable: Vec<Vec<(usize, usize)>>,
@@ -26,6 +33,7 @@ pub struct App {
2633 pub load: bool,
2734 pub render: bool,
2835 pub history: Vec<AppHistory>,
36 pub watch_history: WatchHistory,
2937}
3038
3139impl Default for App {
@@ -43,6 +51,8 @@ impl Default for App {
4351 load: true,
4452 render: true,
4553 history: Vec::new(),
54 config: Config::load().unwrap(),
55 watch_history: WatchHistory::load(),
4656 }
4757 }
4858}
@@ -296,7 +306,13 @@ impl App {
296306
297307 match item {
298308 Item::Global(i) => {
299 i.render_item(frame, chunk, selected, hover, &*self.message.lock().unwrap());
309 i.render_item(
310 frame,
311 chunk,
312 selected,
313 hover,
314 &*self.message.lock().unwrap(),
315 );
300316 }
301317 Item::MainMenu(i) => {
302318 i.render_item(frame, chunk, selected, hover, &self.page);
@@ -309,15 +325,15 @@ impl App {
309325 }
310326 }
311327
312 pub fn pop(&mut self) -> bool{
328 pub fn pop(mut self) -> (App, bool) {
313329 if self.history.len() == 0 {
314330 *self.message.lock().unwrap() = Some(String::from("This is the beginning of history"));
315 return false;
331 return (self, false);
316332 }
317333
318334 let app_history = self.history.pop().unwrap();
319335
320 *self = Self {
336 self = Self {
321337 state: app_history.state,
322338 selectable: app_history.selectable,
323339 selected: app_history.selected,
@@ -328,12 +344,14 @@ impl App {
328344 load: app_history.load,
329345 render: app_history.render,
330346 history: self.history.clone(),
347 config: self.config,
348 watch_history: self.watch_history,
331349 };
332350
333 true
351 (self, true)
334352 }
335353
336354 pub fn home(&mut self) {
337355 *self = App::default();
338356 }
339}
\ No newline at end of file
357}
src/app/config/commands.rs added +118
@@ -0,0 +1,118 @@
1use serde::{Deserialize, Serialize};
2
3use crate::functions::insert_vec;
4
5use super::{Config, EnvVar};
6
7#[derive(Clone, Debug, Serialize, Deserialize)]
8pub struct CommandsConfig {
9 pub video_player: CommandConfig,
10 pub audio_player: CommandConfig,
11 pub image_viewer: CommandConfig,
12 pub video_downloader: CommandConfig,
13 pub audio_downloader: CommandConfig,
14 pub terminal: CommandConfig,
15}
16
17#[derive(Clone, Debug, Serialize, Deserialize)]
18pub struct CommandConfig {
19 pub command: String,
20 pub open_in_console: bool,
21 pub args: Vec<String>,
22}
23
24impl CommandConfig {
25 pub fn as_vec(&self) -> Vec<String> {
26 let mut args = self.args.clone();
27 args.insert(0, self.command.clone());
28 args
29 }
30
31 pub fn as_command_vec(self, env: EnvVar, config: &Config) -> Result<Vec<String>, ()> {
32 let mut out;
33 if self.open_in_console {
34 out = config.commands.terminal.as_vec();
35 let index = match out.iter().position(|x| x == "{command}") {
36 Some(index) => {
37 out.swap_remove(index);
38 index
39 }
40 None => out.len(),
41 };
42
43 insert_vec(&mut out, self.as_vec(), index);
44 } else {
45 out = self.as_vec();
46 }
47
48 for x in out.iter_mut() {
49 match x.as_str() {
50 "{url}" => {
51 if let Some(url) = &env.url {
52 *x = url.clone();
53 } else {
54 return Err(());
55 }
56 }
57
58 "{video_save_location}" => {
59 *x = config.main.yt_dl.video_path.clone();
60 }
61
62 "{audio_save_location}" => {
63 *x = config.main.yt_dl.audio_path.clone();
64 }
65
66 _ => {}
67 }
68 }
69
70 Ok(out)
71 }
72}
73
74impl Default for CommandsConfig {
75 fn default() -> Self {
76 Self {
77 video_player: CommandConfig {
78 command: String::from("mpv"),
79 open_in_console: false,
80 args: vec![String::from("--no-terminal"), String::from("{url}")],
81 },
82 audio_player: CommandConfig {
83 command: String::from("mpv"),
84 open_in_console: true,
85 args: vec![String::from("--no-video"), String::from("{url}")],
86 },
87 image_viewer: CommandConfig {
88 command: String::from("mpv"),
89 open_in_console: false,
90 args: vec![String::from("{url}"), String::from("--no-terminal")],
91 },
92 video_downloader: CommandConfig {
93 command: String::from("yt-dlp"),
94 open_in_console: true,
95 args: vec![
96 String::from("{url}"),
97 String::from("-o"),
98 String::from("{video_save_location}"),
99 ],
100 },
101 audio_downloader: CommandConfig {
102 command: String::from("yt-dlp"),
103 open_in_console: true,
104 args: vec![
105 String::from("{url}"),
106 String::from("-o"),
107 String::from("{audio_save_location}"),
108 String::from("-x"),
109 ],
110 },
111 terminal: CommandConfig {
112 command: String::from("konsole"),
113 open_in_console: false,
114 args: vec![String::from("-e"), String::from("{command}")],
115 },
116 }
117 }
118}
src/app/config/config.rs added +76
@@ -0,0 +1,76 @@
1use std::{
2 error::Error,
3 fs::{self, OpenOptions},
4 io::Write,
5};
6
7use super::{commands::CommandsConfig, MainConfig};
8
9#[derive(Clone, Debug)]
10pub struct Config {
11 pub commands: CommandsConfig,
12 pub main: MainConfig,
13}
14
15impl Default for Config {
16 fn default() -> Self {
17 Self {
18 commands: CommandsConfig::default(),
19 main: MainConfig::default(),
20 }
21 }
22}
23
24impl Config {
25 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 })
65 }
66}
67
68pub struct EnvVar {
69 pub url: Option<String>,
70}
71
72impl Default for EnvVar {
73 fn default() -> Self {
74 Self { url: None }
75 }
76}
src/app/config/main.rs added +31
@@ -0,0 +1,31 @@
1use serde::{Deserialize, Serialize};
2
3#[derive(Clone, Debug, Serialize, Deserialize)]
4pub struct MainConfig {
5 pub yt_dl: YtDlConfig,
6 pub max_watch_history: usize,
7}
8
9impl Default for MainConfig {
10 fn default() -> Self {
11 Self {
12 yt_dl: YtDlConfig::default(),
13 max_watch_history: 50,
14 }
15 }
16}
17
18#[derive(Clone, Debug, Serialize, Deserialize)]
19pub struct YtDlConfig {
20 pub video_path: String,
21 pub audio_path: String,
22}
23
24impl Default for YtDlConfig {
25 fn default() -> Self {
26 Self {
27 video_path: String::from("~/Downloads/%(title)s.%(ext)s"),
28 audio_path: String::from("~/Downloads/%(title)s.%(ext)s"),
29 }
30 }
31}
src/app/config/mod.rs added +7
@@ -0,0 +1,7 @@
1mod commands;
2
3mod config;
4pub use config::*;
5
6mod main;
7pub use main::*;
src/app/mod.rs +2 −1
@@ -1,2 +1,3 @@
11pub mod app;
2pub mod pages;
\ No newline at end of file
2pub mod config;
3pub mod pages;
src/app/pages/global.rs +7 −1
@@ -1,7 +1,13 @@
11use std::fmt;
22
33use crossterm::event::KeyCode;
4use tui::{style::{Color, Style}, widgets::{Borders, Paragraph, BorderType, Block}, layout::{Alignment, Rect}, Frame, backend::Backend};
4use tui::{
5 backend::Backend,
6 layout::{Alignment, Rect},
7 style::{Color, Style},
8 widgets::{Block, BorderType, Borders, Paragraph},
9 Frame,
10};
511
612use crate::{
713 app::app::App,
src/app/pages/item_info.rs +154 −74
@@ -6,8 +6,8 @@ use std::{
66};
77
88use crate::{
9 app::{app::App, pages::global::*},
10 functions::{download_all_thumbnails, ItemType},
9 app::{app::App, config::EnvVar, pages::global::*},
10 functions::download_all_thumbnails,
1111 structs::{FullVideo, Item, ListItem, Page, Row, RowItem},
1212 traits::{KeyInput, LoadItem, SelectItem},
1313 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
@@ -59,88 +59,154 @@ impl KeyInput for ItemInfoItem {
5959 if videoinfo.list.selected < 5 {
6060 *app.message.lock().unwrap() = Some(String::from("Launched application"));
6161 }
62
6263 match videoinfo.list.selected {
6364 0 => {
64 let command = vec![
65 String::from("mpv"),
66 String::from("--no-terminal"),
67 match videoinfo.mode {
68 Mode::Youtube => {
69 format!("https://youtu.be/{}", videoinfo.video.video_id)
70 }
71 Mode::Invidious => {
72 format!(
73 "{}/embed/{}",
74 app.client.server, videoinfo.video.video_id
75 )
65 app.watch_history.push(
66 videoinfo.video.video_id.clone(),
67 ListItem::FullVideo(videoinfo.video.clone()),
68 &app.config,
69 );
70 let command =
71 match app.config.commands.video_player.clone().as_command_vec(
72 EnvVar {
73 url: Some(match videoinfo.mode {
74 Mode::Youtube => {
75 format!(
76 "https://youtu.be/{}",
77 videoinfo.video.video_id
78 )
79 }
80 Mode::Invidious => {
81 format!(
82 "{}/embed/{}",
83 app.client.server, videoinfo.video.video_id
84 )
85 }
86 }),
87 ..Default::default()
88 },
89 &app.config,
90 ) {
91 Ok(command) => command,
92 Err(_) => {
93 *app.message.lock().unwrap() =
94 Some(String::from("Error in parsing launch command"));
95 return (false, app);
7696 }
77 },
78 ];
97 };
7998
8099 run_command(command, app.message.clone());
81100 }
82101 1 => {
83 let command = vec![
84 String::from("konsole"),
85 String::from("-e"),
86 String::from("mpv"),
87 String::from("--no-video"),
88 match videoinfo.mode {
89 Mode::Youtube => {
90 format!("https://youtu.be/{}", videoinfo.video.video_id)
102 app.watch_history.push(
103 videoinfo.video.video_id.clone(),
104 ListItem::FullVideo(videoinfo.video.clone()),
105 &app.config,
106 );
107 let command =
108 match app.config.commands.audio_player.clone().as_command_vec(
109 EnvVar {
110 url: Some(match videoinfo.mode {
111 Mode::Youtube => {
112 format!(
113 "https://youtu.be/{}",
114 videoinfo.video.video_id
115 )
116 }
117 Mode::Invidious => {
118 format!(
119 "{}/embed/{}",
120 app.client.server, videoinfo.video.video_id
121 )
122 }
123 }),
124 ..Default::default()
125 },
126 &app.config,
127 ) {
128 Ok(command) => command,
129 Err(_) => {
130 *app.message.lock().unwrap() =
131 Some(String::from("Error in parsing launch command"));
132 return (false, app);
91133 }
92 Mode::Invidious => {
93 format!(
94 "{}/embed/{}",
95 app.client.server, videoinfo.video.video_id
96 )
97 }
98 },
99 ];
134 };
100135
101136 run_command(command, app.message.clone());
102137 }
103138 2 => {
104 let command = vec![
105 String::from("konsole"),
106 String::from("-e"),
107 String::from("yt-dlp"),
108 match videoinfo.mode {
109 Mode::Youtube => {
110 format!("https://youtu.be/{}", videoinfo.video.video_id)
111 }
112 Mode::Invidious => {
113 format!(
114 "{}/embed/{}",
115 app.client.server, videoinfo.video.video_id
116 )
139 app.watch_history.push(
140 videoinfo.video.video_id.clone(),
141 ListItem::FullVideo(videoinfo.video.clone()),
142 &app.config,
143 );
144 let command =
145 match app.config.commands.video_downloader.clone().as_command_vec(
146 EnvVar {
147 url: Some(match videoinfo.mode {
148 Mode::Youtube => {
149 format!(
150 "https://youtu.be/{}",
151 videoinfo.video.video_id
152 )
153 }
154 Mode::Invidious => {
155 format!(
156 "{}/embed/{}",
157 app.client.server, videoinfo.video.video_id
158 )
159 }
160 }),
161 ..Default::default()
162 },
163 &app.config,
164 ) {
165 Ok(command) => command,
166 Err(_) => {
167 *app.message.lock().unwrap() =
168 Some(String::from("Error in parsing launch command"));
169 return (false, app);
117170 }
118 },
119 String::from("-o"),
120 String::from("~/Downloads/%(title)s.%(ext)s"),
121 ];
171 };
172
122173 run_command(command, app.message.clone());
123174 }
124175 3 => {
125 let command = vec![
126 String::from("konsole"),
127 String::from("-e"),
128 String::from("yt-dlp"),
129 match videoinfo.mode {
130 Mode::Youtube => {
131 format!("https://youtu.be/{}", videoinfo.video.video_id)
132 }
133 Mode::Invidious => {
134 format!(
135 "{}/embed/{}",
136 app.client.server, videoinfo.video.video_id
137 )
176 app.watch_history.push(
177 videoinfo.video.video_id.clone(),
178 ListItem::FullVideo(videoinfo.video.clone()),
179 &app.config,
180 );
181 let command =
182 match app.config.commands.audio_downloader.clone().as_command_vec(
183 EnvVar {
184 url: Some(match videoinfo.mode {
185 Mode::Youtube => {
186 format!(
187 "https://youtu.be/{}",
188 videoinfo.video.video_id
189 )
190 }
191 Mode::Invidious => {
192 format!(
193 "{}/embed/{}",
194 app.client.server, videoinfo.video.video_id
195 )
196 }
197 }),
198 ..Default::default()
199 },
200 &app.config,
201 ) {
202 Ok(command) => command,
203 Err(_) => {
204 *app.message.lock().unwrap() =
205 Some(String::from("Error in parsing launch command"));
206 return (false, app);
138207 }
139 },
140 String::from("-o"),
141 String::from("~/Downloads/%(title)s.%(ext)s"),
142 String::from("-x"),
143 ];
208 };
209
144210 run_command(command, app.message.clone());
145211 }
146212 4 => {
@@ -149,13 +215,28 @@ impl KeyInput for ItemInfoItem {
149215 dir.push(".cache");
150216 dir.push("youtube-tui");
151217 dir.push("thumbnails");
152 dir.push("videos");
153218 dir.push(format!("{}.png", videoinfo.video.video_id));
154 let command = vec![
155 String::from("mpv"),
156 String::from("--no-terminal"),
157 (*dir.as_path().to_string_lossy()).to_string(),
158 ];
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 let command =
226 match app.config.commands.image_viewer.clone().as_command_vec(
227 EnvVar {
228 url: Some((*dir.as_path().to_string_lossy()).to_string()),
229 ..Default::default()
230 },
231 &app.config,
232 ) {
233 Ok(command) => command,
234 Err(_) => {
235 *app.message.lock().unwrap() =
236 Some(String::from("Error in parsing launch command"));
237 return (false, app);
238 }
239 };
159240
160241 run_command(command, app.message.clone());
161242 }
@@ -193,7 +274,6 @@ impl LoadItem for ItemInfoItem {
193274 let _ = download_all_thumbnails(LinkedList::from([(
194275 video.video_thumbnail.clone(),
195276 video.video_id.clone(),
196 ItemType::Video,
197277 )]));
198278 list.items(vec![
199279 String::from("Watch video"),
src/app/pages/main_menu.rs +73 −39
@@ -1,12 +1,14 @@
1use std::{collections::LinkedList, error::Error};
1use std::{collections::LinkedList, error::Error, fs};
22
33use crate::{
44 app::{
5 pages::{global::*, item_info::*}, app::App,
5 app::App,
6 pages::{global::*, item_info::*},
67 },
7 functions::{download_all_thumbnails, ItemType},
8 functions::download_all_thumbnails,
9 structs::{Item, ListItem, Page, Row, RowItem},
810 traits::{KeyInput, LoadItem, SelectItem},
9 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList}, structs::{Page, Row, RowItem, Item, ListItem},
11 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
1012};
1113use crossterm::event::KeyCode;
1214use tui::{
@@ -57,18 +59,21 @@ impl KeyInput for MainMenuItem {
5759 KeyCode::PageDown => list.selected = list.items.len() - 1,
5860 KeyCode::Enter => {
5961 let state = ItemInfo::default();
60 let mut history = app.history.clone();
61 history.push(app.into());
62
63 return (false, App {
64 history,
65 page: Page::ItemDisplay(DisplayItem::Video(
66 video_list.iter().nth(list.selected).unwrap().id(),
67 )),
68 selectable: App::selectable(&state),
69 state,
70 ..Default::default()
71 });
62 let mut history = app.history.clone();
63 history.push(app.into());
64
65 return (
66 false,
67 App {
68 history,
69 page: Page::ItemDisplay(DisplayItem::Video(
70 video_list.iter().nth(list.selected).unwrap().id(),
71 )),
72 selectable: App::selectable(&state),
73 state,
74 ..Default::default()
75 },
76 );
7277 }
7378 _ => {}
7479 },
@@ -95,13 +100,16 @@ impl LoadItem for MainMenuItem {
95100 .map(|t| ListItem::MiniVideo(t.into()))
96101 .collect();
97102
98 download_all_thumbnails(list.iter().map(|t| (
99 match t {
100 ListItem::MiniVideo(v) => (v.video_thumbnail.clone(), v.video_id.clone(), ItemType::Video),
103 download_all_thumbnails(
104 list.iter()
105 .map(|t| match t {
106 ListItem::MiniVideo(v) => {
107 (v.video_thumbnail.clone(), v.video_id.clone())
108 }
101109 _ => unreachable!(),
102
103 }
104 )).collect())?;
110 })
111 .collect(),
112 )?;
105113
106114 if let Some((video_list, text_list, _)) = enum_items {
107115 *text_list = TextList::default();
@@ -124,13 +132,16 @@ impl LoadItem for MainMenuItem {
124132 .map(|t| ListItem::MiniVideo(t.into()))
125133 .collect();
126134
127 download_all_thumbnails(list.iter().map(|t| (
128 match t {
129 ListItem::MiniVideo(v) => (v.video_thumbnail.clone(), v.video_id.clone(), ItemType::Video),
130 _ => unreachable!(),
131
132 }
133 )).collect())?;
135 download_all_thumbnails(
136 list.iter()
137 .map(|t| match t {
138 ListItem::MiniVideo(v) => {
139 (v.video_thumbnail.clone(), v.video_id.clone())
140 }
141 _ => unreachable!(),
142 })
143 .collect(),
144 )?;
134145
135146 let mut text_list = TextList::default();
136147
@@ -145,7 +156,33 @@ impl LoadItem for MainMenuItem {
145156 };
146157 }
147158
148 _ => {}
159 MainMenuSelector::History => {
160 let mut list = LinkedList::new();
161 let mut text_list = TextList::default();
162
163 app.watch_history.0.iter().for_each(|t| {
164 let file = fs::read_to_string(
165 home::home_dir()
166 .expect("Cannot get your home directory")
167 .join(".local/share/youtube-tui/watch_history/info")
168 .join(format!("{}.json", t)),
169 );
170
171 if let Ok(file) = file {
172 let item: ListItem = serde_json::from_str(&file).unwrap();
173
174 let title = match &item {
175 ListItem::FullVideo(v) => v.title.clone(),
176 _ => unreachable!(),
177 };
178
179 list.push_back(item);
180 text_list.items.push(title);
181 }
182 });
183
184 *enum_items = Some((list, text_list, None));
185 }
149186 },
150187
151188 _ => {}
@@ -220,13 +257,10 @@ impl MainMenuItem {
220257 list.selected_style(Style::default().fg(Color::LightYellow));
221258 }
222259
223 let item_info = ItemDisplay {
224 item: videos.iter().nth(list.selected).unwrap().clone(),
225 };
226
227 frame.render_widget(item_info, chunks[1]);
260 if let Some(item) = videos.iter().nth(list.selected) {
261 frame.render_widget(ItemDisplay { item: item.clone() }, chunks[1]);
262 }
228263
229
230264 frame.render_widget(list, chunks[0]);
231265 }
232266 }
@@ -260,7 +294,7 @@ pub enum MainMenuSelector {
260294
261295impl Default for MainMenuSelector {
262296 fn default() -> Self {
263 Self::Trending
297 Self::Popular
264298 }
265299}
266300
@@ -284,11 +318,11 @@ impl MainMenu {
284318 Row {
285319 items: vec![
286320 RowItem {
287 item: Item::MainMenu(MainMenuItem::SeletorTab(MainMenuSelector::Trending)),
321 item: Item::MainMenu(MainMenuItem::SeletorTab(MainMenuSelector::Popular)),
288322 constraint: Constraint::Length(15),
289323 },
290324 RowItem {
291 item: Item::MainMenu(MainMenuItem::SeletorTab(MainMenuSelector::Popular)),
325 item: Item::MainMenu(MainMenuItem::SeletorTab(MainMenuSelector::Trending)),
292326 constraint: Constraint::Length(15),
293327 },
294328 RowItem {
src/app/pages/mod.rs +2 −2
@@ -1,3 +1,3 @@
1pub mod main_menu;
21pub mod global;
3pub mod item_info;
\ No newline at end of file
2pub mod item_info;
3pub mod main_menu;
src/functions/download_all_thumbnails.rs +5 −8
@@ -9,7 +9,7 @@ pub enum ItemType {
99}
1010
1111pub fn download_all_thumbnails(
12 list: LinkedList<(String, String, ItemType)>,
12 list: LinkedList<(String, String)>,
1313) -> Result<(), Box<dyn Error>> {
1414 thread::spawn(move || {
1515 let rt: Runtime = tokio::runtime::Runtime::new().unwrap();
@@ -20,18 +20,16 @@ pub fn download_all_thumbnails(
2020 Ok(())
2121}
2222
23pub async fn download_items(urls: LinkedList<(String, String, ItemType)>) -> Result<(), Box<dyn Error>> {
23pub async fn download_items(
24 urls: LinkedList<(String, String)>,
25) -> Result<(), Box<dyn Error>> {
2426 let mut actions = Vec::new();
2527 let mut path = home::home_dir().expect("Cannot get your home directory");
2628 path.push(".cache");
2729 path.push("youtube-tui");
2830 path.push("thumbnails");
2931
30 for (url, video_id, item_type) in urls.iter() {
31 path.push(match item_type {
32 ItemType::Video => "videos",
33 ItemType::Playlist => "playlists",
34 });
32 for (url, video_id) in urls.iter() {
3533
3634 path.push(format!("{}.png", video_id));
3735
@@ -43,7 +41,6 @@ pub async fn download_items(urls: LinkedList<(String, String, ItemType)>) -> Res
4341 }
4442
4543 path.pop();
46 path.pop();
4744 }
4845
4946 join_all(actions).await;
src/functions/insert_vec.rs added +6
@@ -0,0 +1,6 @@
1pub fn insert_vec<T>(vec: &mut Vec<T>, to_insert: Vec<T>, mut index: usize) {
2 to_insert.into_iter().for_each(|x| {
3 vec.insert(index, x);
4 index += 1;
5 });
6}
src/functions/mod.rs +4 −1
@@ -1,2 +1,5 @@
11mod download_all_thumbnails;
2pub use download_all_thumbnails::*;
\ No newline at end of file
2pub use download_all_thumbnails::*;
3
4mod insert_vec;
5pub use insert_vec::*;
\ No newline at end of file
src/lib.rs +2 −2
@@ -1,5 +1,5 @@
11pub mod app;
2pub mod functions;
3pub mod structs;
24pub mod traits;
35pub mod widgets;
4pub mod functions;
5pub mod structs;
\ No newline at end of file
src/main.rs +49 −4
@@ -120,7 +120,9 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
120120 return Ok(());
121121 }
122122 KeyCode::Backspace => {
123 if app.pop() {
123 let holder = app.pop();
124 app = holder.0;
125 if holder.1 {
124126 terminal.clear()?;
125127 }
126128 app.render = true;
@@ -163,7 +165,9 @@ fn ui<B: Backend>(terminal: &mut Terminal<B>, app: &mut App) -> Result<(), Box<d
163165}
164166
165167fn init() -> Result<(), Box<dyn Error>> {
166 let mut dir = home::home_dir().expect("Cannot get your home directory");
168 let home_dir = home::home_dir().expect("Cannot get your home directory");
169
170 let mut dir = home_dir.clone();
167171
168172 dir.push(".cache");
169173 if !dir.exists() {
@@ -181,7 +185,47 @@ fn init() -> Result<(), Box<dyn Error>> {
181185 fs::create_dir(&dir)?;
182186 }
183187
184 dir.push("videos");
188 dir = home_dir.clone();
189
190 dir.push(".config");
191
192 if !dir.exists() {
193 fs::create_dir(&dir)?;
194 }
195
196 dir.push("youtube-tui");
197
198 if !dir.exists() {
199 fs::create_dir(&dir)?;
200 }
201
202 dir = home_dir;
203
204 dir.push(".local");
205
206 if !dir.exists() {
207 fs::create_dir(&dir)?;
208 }
209
210 dir.push("share");
211
212 if !dir.exists() {
213 fs::create_dir(&dir)?;
214 }
215
216 dir.push("youtube-tui");
217
218 if !dir.exists() {
219 fs::create_dir(&dir)?;
220 }
221
222 dir.push("watch_history");
223
224 if !dir.exists() {
225 fs::create_dir(&dir)?;
226 }
227
228 dir.push("thumbnails");
185229
186230 if !dir.exists() {
187231 fs::create_dir(&dir)?;
@@ -189,12 +233,13 @@ fn init() -> Result<(), Box<dyn Error>> {
189233
190234 dir.pop();
191235
192 dir.push("playlists");
236 dir.push("info");
193237
194238 if !dir.exists() {
195239 fs::create_dir(&dir)?;
196240 }
197241
242
198243 Ok(())
199244}
200245
src/structs/fullvideo.rs +8 −3
@@ -1,8 +1,9 @@
1use chrono::{Utc, NaiveDateTime, DateTime};
1use chrono::{DateTime, NaiveDateTime, Utc};
22use invidious::structs::video::Video;
33use thousands::Separable;
4use serde::{Deserialize, Serialize};
45
5#[derive(Debug, Clone)]
6#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct FullVideo {
78 pub title: String,
89 pub video_id: String,
@@ -52,7 +53,11 @@ impl From<Video> for FullVideo {
5253 public: original.isListed,
5354 live: original.liveNow,
5455 upcoming: original.isUpcoming,
55 recommendations: original.recommendedVideos.into_iter().map(|x| x.videoId).collect(),
56 recommendations: original
57 .recommendedVideos
58 .into_iter()
59 .map(|x| x.videoId)
60 .collect(),
5661 }
5762 }
5863}
src/structs/listitem.rs +3 −3
@@ -1,7 +1,7 @@
1use crate::structs::{FullVideo, MiniVideo};
2use serde::{Deserialize, Serialize};
13
2use crate::structs::{MiniVideo, FullVideo};
3
4#[derive(Debug, Clone)]
4#[derive(Debug, Clone, Deserialize, Serialize)]
55pub enum ListItem {
66 MiniVideo(MiniVideo),
77 FullVideo(FullVideo),
src/structs/minivideo.rs +4 −3
@@ -1,8 +1,9 @@
1use thousands::Separable;
21use chrono::{prelude::*, Utc};
32use invidious::structs::hidden::{PopularItem, TrendingVideo};
3use thousands::Separable;
4use serde::{Deserialize, Serialize};
45
5#[derive(Debug, Clone)]
6#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct MiniVideo {
78 pub title: String,
89 pub video_id: String,
@@ -61,7 +62,7 @@ impl From<PopularItem> for MiniVideo {
6162 NaiveDateTime::from_timestamp(original.published as i64, 0),
6263 Utc,
6364 );
64 format!("[{}]", datetime.format("%Y/%m/%d"))
65 format!(" [{}]", datetime.format("%Y/%m/%d"))
6566 } else {
6667 String::new()
6768 }
src/structs/mod.rs +4 −1
@@ -14,4 +14,7 @@ mod minivideo;
1414pub use minivideo::*;
1515
1616mod fullvideo;
17pub use fullvideo::*;
\ No newline at end of file
17pub use fullvideo::*;
18
19mod watchhistory;
20pub use watchhistory::*;
\ No newline at end of file
src/structs/page.rs +2 −2
@@ -1,4 +1,4 @@
1use crate::app::pages::{main_menu::MainMenuSelector, item_info::DisplayItem};
1use crate::app::pages::{item_info::DisplayItem, main_menu::MainMenuSelector};
22
33#[derive(Debug, PartialEq, Clone)]
44pub enum Page {
@@ -10,4 +10,4 @@ impl Default for Page {
1010 fn default() -> Self {
1111 Self::MainMenu(MainMenuSelector::default())
1212 }
13}
\ No newline at end of file
13}
src/structs/states.rs +2 −2
@@ -1,6 +1,6 @@
11use tui::layout::Constraint;
22
3use crate::app::pages::{global::GlobalItem, main_menu::MainMenuItem, item_info::ItemInfoItem};
3use crate::app::pages::{global::GlobalItem, item_info::ItemInfoItem, main_menu::MainMenuItem};
44
55#[derive(Debug, Clone)]
66pub enum Item {
@@ -20,4 +20,4 @@ pub struct Row {
2020pub struct RowItem {
2121 pub item: Item,
2222 pub constraint: Constraint,
23}
\ No newline at end of file
23}
src/structs/watchhistory.rs added +93
@@ -0,0 +1,93 @@
1use std::{collections::LinkedList, fs};
2
3use serde::{Deserialize, Serialize};
4
5use crate::app::config::Config;
6
7use super::ListItem;
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct WatchHistory(pub LinkedList<String>);
11
12
13
14impl Default for WatchHistory {
15 fn default() -> Self {
16 WatchHistory(LinkedList::new())
17 }
18}
19
20impl WatchHistory {
21 pub fn load() -> Self {
22 let mut dir = home::home_dir().expect("Cannot get your home directory");
23 dir = dir.join(".local/share/youtube-tui/watch_history/watch_history.json");
24
25 if !dir.exists() {
26 let out = Self::default();
27
28 fs::write(dir, serde_json::to_string(&out).unwrap())
29 .expect("Cannot write watch history");
30
31 return out;
32 }
33
34 let contents = fs::read_to_string(dir).expect("Cannot read watch history file");
35
36 serde_json::from_str(&contents).expect("Cannot parse watch history file")
37 }
38
39 pub fn push(&mut self, item: String, listitem: ListItem, config: &Config) {
40 if let Some(v) = self.0.front() {
41 if *v == item {
42 return;
43 }
44 }
45 self.0.push_front(item);
46
47 let home_dir = home::home_dir().expect("Cannot get your home directory");
48
49 let mut original_dir = home_dir.join(".cache/youtube-tui/thumbnails");
50
51 match &listitem {
52 ListItem::FullVideo(video) => {
53 let mut save_file = home_dir.join(".local/share/youtube-tui/watch_history/info");
54 save_file.push(format!("{}.json", video.video_id));
55 fs::write(save_file, serde_json::to_string(&listitem).unwrap()).unwrap();
56
57 let file_name = format!("{}.png", video.video_id);
58 original_dir.push(file_name.clone());
59
60 if original_dir.exists() {
61 let mut new_dir =
62 home_dir.join(".local/share/youtube-tui/watch_history/thumbnails");
63 new_dir.push(file_name);
64
65 if !new_dir.exists() {
66 fs::copy(original_dir, new_dir).expect("Cannot copy thumbnail");
67 }
68 }
69 }
70 _ => {}
71 }
72
73 fs::write(
74 home_dir.join(".local/share/youtube-tui/watch_history/watch_history.json"),
75 serde_json::to_string(&self).unwrap(),
76 )
77 .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 }
93}
\ No newline at end of file
src/traits/key_input.rs +3 −3
@@ -1,6 +1,6 @@
1use crossterm::event::KeyCode;
21use crate::app::app::App;
2use crossterm::event::KeyCode;
33
44pub trait KeyInput {
5 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) ;
6}
\ No newline at end of file
5 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App);
6}
src/traits/mod.rs +1 −1
@@ -5,4 +5,4 @@ mod key_input;
55pub use key_input::*;
66
77mod load_item;
8pub use load_item::*;
\ No newline at end of file
8pub use load_item::*;
src/traits/select_item.rs +1 −1
@@ -3,4 +3,4 @@ use crate::app::app::App;
33pub trait SelectItem {
44 fn select(&mut self, app: App) -> (App, bool);
55 fn selectable(&self) -> bool;
6}
\ No newline at end of file
6}
src/widgets/horizontal_split.rs +1 −1
@@ -152,7 +152,7 @@ impl HorizontalSplit {
152152 .collect::<Vec<_>>()
153153 }
154154
155 pub fn percentages(self, percentages: Vec<usize>) -> Self{
155 pub fn percentages(self, percentages: Vec<usize>) -> Self {
156156 Self {
157157 percentages,
158158 ..self
src/widgets/item_display.rs +3 −5
@@ -1,8 +1,8 @@
11use tui::{
22 buffer::Buffer,
3 layout::{Margin, Rect},
3 layout::Rect,
44 style::{Color, Style},
5 widgets::{Block, Borders, Widget},
5 widgets::Widget,
66};
77use viuer::{print_from_file, Config};
88
@@ -21,7 +21,6 @@ impl Widget for ItemDisplay {
2121 path.push(".cache");
2222 path.push("youtube-tui");
2323 path.push("thumbnails");
24 path.push("videos");
2524 path.push(format!("{}.png", video.video_id));
2625 let exists = path.exists();
2726 let mut image_transform = area;
@@ -86,7 +85,6 @@ impl Widget for ItemDisplay {
8685 path.push(".cache");
8786 path.push("youtube-tui");
8887 path.push("thumbnails");
89 path.push("videos");
9088 path.push(format!("{}.png", video.video_id));
9189 let exists = path.exists();
9290 let mut image_transform = area;
@@ -135,7 +133,7 @@ impl Widget for ItemDisplay {
135133 tags.push("Video");
136134
137135 to_print.push((
138 format!("[{}]", tags.join(" ")),
136 format!(" [{}]", tags.join(" ")),
139137 Style::default().fg(Color::Gray),
140138 ));
141139 to_print.push((video.title, Style::default().fg(Color::LightBlue)));
src/widgets/mod.rs +2 −2
@@ -1,3 +1,3 @@
1pub mod text_list;
21pub mod horizontal_split;
3pub mod item_display;
\ No newline at end of file
2pub mod item_display;
3pub mod text_list;
src/widgets/text_list.rs +1 −1
@@ -21,7 +21,7 @@ pub struct TextList {
2121
2222impl Widget for TextList {
2323 fn render(self, area: Rect, buf: &mut Buffer) {
24 if self.items.len() == 0 || area.height < 3{
24 if self.items.len() == 0 || area.height < 3 {
2525 return;
2626 }
2727