Commit 9ee11b5b58

9ee11b5b5875f80d5541f8ea6451e853d0aa3cdf

parent: 7b5aa671fe

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2023-02-14 20:33 UTC

shows cached version of item when selected from watch history page

Layout: unified · split

Cargo.lock +1 −1
@@ -1923,7 +1923,7 @@ dependencies = [
1923 1923
1924[[package]] 1924[[package]]
1925name = "youtube-tui" 1925name = "youtube-tui"
1926version = "0.6.2" 1926version = "0.7.0"
1927dependencies = [ 1927dependencies = [
1928 "chrono", 1928 "chrono",
1929 "clipboard", 1929 "clipboard",
Cargo.toml +1 −1
@@ -1,6 +1,6 @@
1[package] 1[package]
2name = "youtube-tui" 2name = "youtube-tui"
3version = "0.6.2" 3version = "0.7.0"
4authors = ["Siriusmart <siriusmart@tuta.io>"] 4authors = ["Siriusmart <siriusmart@tuta.io>"]
5edition = "2021" 5edition = "2021"
6description = "An aesthetically pleasing YouTube TUI written in Rust" 6description = "An aesthetically pleasing YouTube TUI written in Rust"
src/config/commandbindings.rs +26 −2
@@ -22,6 +22,8 @@ pub struct CommandBindings {
22 pub channel_videos: HashMap<KeyCode, HashMap<u8, String>>, 22 pub channel_videos: HashMap<KeyCode, HashMap<u8, String>>,
23 pub channel_playlists: HashMap<KeyCode, HashMap<u8, String>>, 23 pub channel_playlists: HashMap<KeyCode, HashMap<u8, String>>,
24 pub watchhistory: HashMap<KeyCode, HashMap<u8, String>>, 24 pub watchhistory: HashMap<KeyCode, HashMap<u8, String>>,
25 pub subscriptions: HashMap<KeyCode, HashMap<u8, String>>,
26 pub libray: HashMap<KeyCode, HashMap<u8, String>>,
25} 27}
26 28
27impl Key for CommandBindings { 29impl Key for CommandBindings {
@@ -41,8 +43,14 @@ impl CommandBindings {
41 Page::MainMenu(MainMenuPage::Trending) => get_command(key, &self.trending), 43 Page::MainMenu(MainMenuPage::Trending) => get_command(key, &self.trending),
42 Page::MainMenu(MainMenuPage::Popular) => get_command(key, &self.popular), 44 Page::MainMenu(MainMenuPage::Popular) => get_command(key, &self.popular),
43 Page::MainMenu(MainMenuPage::History) => get_command(key, &self.watchhistory), 45 Page::MainMenu(MainMenuPage::History) => get_command(key, &self.watchhistory),
44 Page::SingleItem(SingleItemPage::Video(_)) => get_command(key, &self.video), 46 Page::MainMenu(MainMenuPage::Subscriptions) => get_command(key, &self.subscriptions),
45 Page::SingleItem(SingleItemPage::Playlist(_)) => get_command(key, &self.playlist), 47 Page::MainMenu(MainMenuPage::Library) => get_command(key, &self.libray),
48 Page::SingleItem(SingleItemPage::Video(_))
49 | Page::SingleItem(SingleItemPage::LocalVideo(_)) => get_command(key, &self.video),
50 Page::SingleItem(SingleItemPage::Playlist(_))
51 | Page::SingleItem(SingleItemPage::LocalPlaylist(_)) => {
52 get_command(key, &self.playlist)
53 }
46 Page::ChannelDisplay(ChannelDisplayPage { 54 Page::ChannelDisplay(ChannelDisplayPage {
47 r#type: ChannelDisplayPageType::Main, 55 r#type: ChannelDisplayPageType::Main,
48 .. 56 ..
@@ -90,6 +98,10 @@ pub struct CommandBindingsSerde {
90 pub channel_playlists: HashMap<KeyCodeSerde, HashMap<u8, String>>, 98 pub channel_playlists: HashMap<KeyCodeSerde, HashMap<u8, String>>,
91 #[serde(default = "watchhistory_default")] 99 #[serde(default = "watchhistory_default")]
92 pub watchhistory: HashMap<KeyCodeSerde, HashMap<u8, String>>, 100 pub watchhistory: HashMap<KeyCodeSerde, HashMap<u8, String>>,
101 #[serde(default = "subscriptions_default")]
102 pub subscriptions: HashMap<KeyCodeSerde, HashMap<u8, String>>,
103 #[serde(default = "library_default")]
104 pub library: HashMap<KeyCodeSerde, HashMap<u8, String>>,
93} 105}
94 106
95impl ConfigTrait for CommandBindingsSerde { 107impl ConfigTrait for CommandBindingsSerde {
@@ -109,6 +121,8 @@ impl CommandBindingsSerde {
109 video: de_serde(self.video)?, 121 video: de_serde(self.video)?,
110 trending: de_serde(self.trending)?, 122 trending: de_serde(self.trending)?,
111 watchhistory: de_serde(self.watchhistory)?, 123 watchhistory: de_serde(self.watchhistory)?,
124 subscriptions: de_serde(self.subscriptions)?,
125 libray: de_serde(self.library)?,
112 }) 126 })
113 } 127 }
114} 128}
@@ -126,6 +140,8 @@ impl Default for CommandBindingsSerde {
126 video: video_default(), 140 video: video_default(),
127 trending: trending_default(), 141 trending: trending_default(),
128 watchhistory: watchhistory_default(), 142 watchhistory: watchhistory_default(),
143 subscriptions: subscriptions_default(),
144 library: library_default(),
129 } 145 }
130 } 146 }
131} 147}
@@ -228,3 +244,11 @@ fn watchhistory_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
228 (KeyCodeSerde::Char('p'), HashMap::from([(2, String::from("run mpv '${hover-url}'"))])) 244 (KeyCodeSerde::Char('p'), HashMap::from([(2, String::from("run mpv '${hover-url}'"))]))
229 ]) 245 ])
230} 246}
247
248fn subscriptions_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
249 HashMap::default()
250}
251
252fn library_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
253 HashMap::default()
254}
src/config/commands.rs +111
@@ -11,6 +11,8 @@ pub struct CommandsConfig {
11 pub launch_command: String, 11 pub launch_command: String,
12 pub video: Vec<(String, String)>, 12 pub video: Vec<(String, String)>,
13 pub playlist: Vec<(String, String)>, 13 pub playlist: Vec<(String, String)>,
14 pub local_video: Vec<(String, String)>,
15 pub local_playlist: Vec<(String, String)>,
14} 16}
15 17
16impl Key for CommandsConfig { 18impl Key for CommandsConfig {
@@ -31,6 +33,16 @@ impl From<CommandsConfigSerde> for CommandsConfig {
31 .into_iter() 33 .into_iter()
32 .map(|hashmap| hashmap.into_iter().last().unwrap()) 34 .map(|hashmap| hashmap.into_iter().last().unwrap())
33 .collect(), 35 .collect(),
36 local_video: original
37 .local_video
38 .into_iter()
39 .map(|hashmap| hashmap.into_iter().last().unwrap())
40 .collect(),
41 local_playlist: original
42 .local_playlist
43 .into_iter()
44 .map(|hashmap| hashmap.into_iter().last().unwrap())
45 .collect(),
34 } 46 }
35 } 47 }
36} 48}
@@ -45,6 +57,10 @@ pub struct CommandsConfigSerde {
45 pub video: Vec<HashMap<String, String>>, 57 pub video: Vec<HashMap<String, String>>,
46 #[serde(default = "playlist_default")] 58 #[serde(default = "playlist_default")]
47 pub playlist: Vec<HashMap<String, String>>, 59 pub playlist: Vec<HashMap<String, String>>,
60 #[serde(default = "local_video_default")]
61 pub local_video: Vec<HashMap<String, String>>,
62 #[serde(default = "local_playlist_default")]
63 pub local_playlist: Vec<HashMap<String, String>>,
48} 64}
49 65
50impl ConfigTrait for CommandsConfigSerde { 66impl ConfigTrait for CommandsConfigSerde {
@@ -57,6 +73,8 @@ impl Default for CommandsConfigSerde {
57 launch_command: launch_command_default(), 73 launch_command: launch_command_default(),
58 video: video_default(), 74 video: video_default(),
59 playlist: playlist_default(), 75 playlist: playlist_default(),
76 local_video: local_video_default(),
77 local_playlist: local_playlist_default(),
60 } 78 }
61 } 79 }
62} 80}
@@ -152,3 +170,96 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
152 )]), 170 )]),
153 ] 171 ]
154} 172}
173
174fn local_video_default() -> Vec<HashMap<String, String>> {
175 vec![
176 HashMap::from([(
177 String::from("Reload as online mode"),
178 String::from("video ${id}"),
179 )]),
180 HashMap::from([(
181 String::from("Play video"),
182 String::from("run ${video-player} '${embed-url}'"),
183 )]),
184 HashMap::from([(
185 String::from("Play audio"),
186 String::from("run ${terminal-emulator} ${video-player} '${embed-url}' --no-video"),
187 )]),
188 HashMap::from([(
189 String::from("Play audio (loop)"),
190 String::from(
191 "run ${terminal-emulator} ${video-player} '${embed-url}' --no-video --loop-file=inf",
192 ),
193 )]),
194 HashMap::from([(
195 String::from("View channel"),
196 String::from("channel ${channel-id}"),
197 )]),
198 HashMap::from([(
199 String::from("Open in browser"),
200 String::from("run ${browser} '${url}'"),
201 )]),
202 HashMap::from([(
203 String::from("Download video (webm)"),
204 String::from(
205 "run ${terminal-emulator} ${youtube-downloader} -o ${download-path} '${embed-url}'",
206 ),
207 )]),
208 HashMap::from([(
209 String::from("Download audio (opus)"),
210 String::from(
211 "run ${terminal-emulator} ${youtube-downloader} -o ${download-path} '${embed-url}' -x",
212 ),
213 )]),
214 HashMap::from([(
215 String::from("Mode: ${provider}"),
216 String::from("switchprovider"),
217 )]),
218 ]
219}
220
221fn local_playlist_default() -> Vec<HashMap<String, String>> {
222 vec![
223 HashMap::from([(String::from("Switch view"), String::from("%switch-view%"))]),
224 HashMap::from([(
225 String::from("Reload as online mode"),
226 String::from("playlist ${id}"),
227 )]),
228 HashMap::from([(
229 String::from("Play all videos"),
230 String::from("run ${video-player} ${all-videos}"),
231 )]),
232 HashMap::from([(
233 String::from("Play all audio"),
234 String::from("run ${terminal-emulator} ${video-player} ${all-videos} --no-video"),
235 )]),
236 HashMap::from([(
237 String::from("Shuffle play all audio"),
238 String::from("run ${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle"),
239 )]),
240 HashMap::from([(
241 String::from("Shuffle play all audio (loop)"),
242 String::from("run ${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle --loop-playlist=inf"),
243 )]),
244 HashMap::from([(
245 String::from("View channel"),
246 String::from("channel ${channel-id}"),
247 )]),
248 HashMap::from([(
249 String::from("Open in browser"),
250 String::from("run ${browser} '${url}'"),
251 )]),
252 HashMap::from([(
253 String::from("Download all video (webm)"),
254 String::from("run ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${all-videos}")
255 )]),
256 HashMap::from([(
257 String::from("Download all audio (opus)"),
258 String::from("run ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${all-videos} -x")
259 )]),
260 HashMap::from([(
261 String::from("Mode: ${provider}"),
262 String::from("switchprovider"),
263 )]),
264 ]
265}
src/config/pages.rs +11 −1
@@ -169,6 +169,10 @@ pub enum PageItems {
169 Popular, 169 Popular,
170 /// the history button which loads the watch history page 170 /// the history button which loads the watch history page
171 History, 171 History,
172 /// the subscriptions button which loads the subscriptions page
173 Subscriptions,
174 /// the library button which loads the saved page
175 Library,
172 /// the search filters `...` button, displays a popup when selected 176 /// the search filters `...` button, displays a popup when selected
173 SearchFilters, 177 SearchFilters,
174 /// playlist and video info display 178 /// playlist and video info display
@@ -191,6 +195,8 @@ impl PageItems {
191 Self::Popular => Box::new(PageButton::Popular), 195 Self::Popular => Box::new(PageButton::Popular),
192 Self::Trending => Box::new(PageButton::Trending), 196 Self::Trending => Box::new(PageButton::Trending),
193 Self::History => Box::new(PageButton::History), 197 Self::History => Box::new(PageButton::History),
198 Self::Subscriptions => Box::new(PageButton::Subscriptions),
199 Self::Library => Box::new(PageButton::Library),
194 Self::MessageBar => Box::<MessageBar>::default(), 200 Self::MessageBar => Box::<MessageBar>::default(),
195 Self::ItemList => Box::<ItemList>::default(), 201 Self::ItemList => Box::<ItemList>::default(),
196 Self::SearchFilters => Box::<SearchFilter>::default(), 202 Self::SearchFilters => Box::<SearchFilter>::default(),
@@ -207,6 +213,8 @@ impl PageItems {
207 Self::Popular 213 Self::Popular
208 | Self::Trending 214 | Self::Trending
209 | Self::History 215 | Self::History
216 | Self::Subscriptions
217 | Self::Library
210 | Self::ChannelMain 218 | Self::ChannelMain
211 | Self::ChannelVideos 219 | Self::ChannelVideos
212 | Self::ChannelPlaylists => Constraint::Length(15), 220 | Self::ChannelPlaylists => Constraint::Length(15),
@@ -221,6 +229,8 @@ impl PageItems {
221 match self { 229 match self {
222 Self::Popular 230 Self::Popular
223 | Self::History 231 | Self::History
232 | Self::Subscriptions
233 | Self::Library
224 | Self::ChannelMain 234 | Self::ChannelMain
225 | Self::ChannelVideos 235 | Self::ChannelVideos
226 | Self::ChannelPlaylists 236 | Self::ChannelPlaylists
@@ -262,7 +272,7 @@ fn main_menu_default() -> PageConfig {
262 layout: vec![ 272 layout: vec![
263 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false), 273 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
264 PageRow::from_vec( 274 PageRow::from_vec(
265 vec![PageItems::Popular, PageItems::Trending, PageItems::History], 275 vec![PageItems::Popular, PageItems::Library, PageItems::History],
266 true, 276 true,
267 ), 277 ),
268 PageRow::from_vec(vec![PageItems::ItemList], false), 278 PageRow::from_vec(vec![PageItems::ItemList], false),
src/global/functions/from_url.rs +7 −11
@@ -11,15 +11,13 @@ pub fn from_channel_url(identifier: &str) -> Result<String, String> {
11 // contained a channel id 11 // contained a channel id
12 if identifier.len() < index + 33 { 12 if identifier.len() < index + 33 {
13 return Err(format!( 13 return Err(format!(
14 "Cannot find channel id from string `{}`", 14 "Cannot find channel id from string `{identifier}`"
15 identifier
16 )); 15 ));
17 } 16 }
18 index + 9 17 index + 9
19 } else { 18 } else {
20 return Err(format!( 19 return Err(format!(
21 "Cannot find channel id from string `{}`", 20 "Cannot find channel id from string `{identifier}`"
22 identifier
23 )); 21 ));
24 }; 22 };
25 23
@@ -36,17 +34,17 @@ pub fn from_video_url(identifier: &str) -> Result<String, String> {
36 // the id can come after "?v=" in an url 34 // the id can come after "?v=" in an url
37 let index = if let Some(index) = identifier.find("?v=") { 35 let index = if let Some(index) = identifier.find("?v=") {
38 if identifier.len() < index + 15 { 36 if identifier.len() < index + 15 {
39 return Err(format!("Cannot find video id from string `{}`", identifier)); 37 return Err(format!("Cannot find video id from string `{identifier}`"));
40 } 38 }
41 index + 3 39 index + 3
42 // and also "youtu.be/" 40 // and also "youtu.be/"
43 } else if let Some(index) = identifier.find("youtu.be/") { 41 } else if let Some(index) = identifier.find("youtu.be/") {
44 if identifier.len() < index + 21 { 42 if identifier.len() < index + 21 {
45 return Err(format!("Cannot find video id from string `{}`", identifier)); 43 return Err(format!("Cannot find video id from string `{identifier}`"));
46 } 44 }
47 index + 9 45 index + 9
48 } else { 46 } else {
49 return Err(format!("Cannot find video id from string `{}`", identifier)); 47 return Err(format!("Cannot find video id from string `{identifier}`"));
50 }; 48 };
51 49
52 Ok(identifier[index..index + 11].to_string()) 50 Ok(identifier[index..index + 11].to_string())
@@ -63,15 +61,13 @@ pub fn from_playlist_url(identifier: &str) -> Result<String, String> {
63 let index = if let Some(index) = identifier.find("list=") { 61 let index = if let Some(index) = identifier.find("list=") {
64 if identifier.len() < index + 39 { 62 if identifier.len() < index + 39 {
65 return Err(format!( 63 return Err(format!(
66 "Cannot find plalyist id from string `{}`", 64 "Cannot find plalyist id from string `{identifier}`"
67 identifier
68 )); 65 ));
69 } 66 }
70 index + 5 67 index + 5
71 } else { 68 } else {
72 return Err(format!( 69 return Err(format!(
73 "Cannot find playlist id from string `{}`", 70 "Cannot find playlist id from string `{identifier}`"
74 identifier
75 )); 71 ));
76 }; 72 };
77 73
src/global/functions/run_command.rs +10
@@ -83,6 +83,8 @@ pub fn run_single_command(
83 "popular" => Some(Page::MainMenu(MainMenuPage::Popular)), 83 "popular" => Some(Page::MainMenu(MainMenuPage::Popular)),
84 "trending" => Some(Page::MainMenu(MainMenuPage::Trending)), 84 "trending" => Some(Page::MainMenu(MainMenuPage::Trending)),
85 "watchhistory" => Some(Page::MainMenu(MainMenuPage::History)), 85 "watchhistory" => Some(Page::MainMenu(MainMenuPage::History)),
86 "subscriptions" => Some(Page::MainMenu(MainMenuPage::Subscriptions)),
87 "library" => Some(Page::MainMenu(MainMenuPage::Library)),
86 "channel" => { 88 "channel" => {
87 if command.len() == 2 { 89 if command.len() == 2 {
88 *framework.data.global.get_mut::<Message>().unwrap() = 90 *framework.data.global.get_mut::<Message>().unwrap() =
@@ -169,6 +171,11 @@ pub fn run_single_command(
169 ["popular"] => run_single_command(&["loadpage", "popular"], framework, terminal), 171 ["popular"] => run_single_command(&["loadpage", "popular"], framework, terminal),
170 ["trending"] => run_single_command(&["loadpage", "trending"], framework, terminal), 172 ["trending"] => run_single_command(&["loadpage", "trending"], framework, terminal),
171 ["watchhistory"] => run_single_command(&["loadpage", "watchhistory"], framework, terminal), 173 ["watchhistory"] => run_single_command(&["loadpage", "watchhistory"], framework, terminal),
174 ["subscriptions"] => {
175 run_single_command(&["loadpage", "subscriptions"], framework, terminal)
176 }
177 ["bookmarks"] => run_single_command(&["loadpage", "bookmarks"], framework, terminal),
178 ["library"] => run_single_command(&["loadpage", "library"], framework, terminal),
172 ["search"] => run_single_command(&["loadpage", "search"], framework, terminal), 179 ["search"] => run_single_command(&["loadpage", "search"], framework, terminal),
173 ["search", ..] => run_single_command( 180 ["search", ..] => run_single_command(
174 &format!("loadpage search {}", command[1..].join(" ")) 181 &format!("loadpage search {}", command[1..].join(" "))
@@ -334,6 +341,9 @@ const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
334 \x1b[33mloadpage popular\x1b[0m Loads the popular videos page 341 \x1b[33mloadpage popular\x1b[0m Loads the popular videos page
335 \x1b[33mloadpage trending\x1b[0m Loads the trending videos page 342 \x1b[33mloadpage trending\x1b[0m Loads the trending videos page
336 \x1b[33mloadpage watchhistory\x1b[0m Loads the watch history page 343 \x1b[33mloadpage watchhistory\x1b[0m Loads the watch history page
344 \x1b[33mloadpage subscriptions\x1b[0m Loads the subscriptions page
345 \x1b[33mloadpage bookmarks\x1b[0m Loads the bookmarks page
346 \x1b[33mloadpage library\x1b[0m Loads the library (saved items) page
337 \x1b[33mloadpage search [query]\x1b[0m Loads the search page with the given query 347 \x1b[33mloadpage search [query]\x1b[0m Loads the search page with the given query
338 \x1b[33mloadpage video [identifier]\x1b[0m Loads the video item page 348 \x1b[33mloadpage video [identifier]\x1b[0m Loads the video item page
339 \x1b[33mloadpage playlist [identifier]\x1b[0m Loads the playlist item page 349 \x1b[33mloadpage playlist [identifier]\x1b[0m Loads the playlist item page
src/global/functions/secs_display_string.rs +2 −2
@@ -8,7 +8,7 @@ pub fn secs_display_string(mut secs: u32) -> String {
8 if secs >= SECS_IN_HOUR { 8 if secs >= SECS_IN_HOUR {
9 let hours = secs / SECS_IN_HOUR; 9 let hours = secs / SECS_IN_HOUR;
10 secs -= hours * SECS_IN_HOUR; 10 secs -= hours * SECS_IN_HOUR;
11 out.push(format!("{}", hours)); 11 out.push(hours.to_string());
12 } 12 }
13 13
14 if secs >= SECS_IN_MINUTE { 14 if secs >= SECS_IN_MINUTE {
@@ -28,7 +28,7 @@ pub fn secs_display_string(mut secs: u32) -> String {
28} 28}
29 29
30fn two_digit_num(num: u32) -> String { 30fn two_digit_num(num: u32) -> String {
31 let out = format!("{}", num); 31 let out = num.to_string();
32 32
33 format!("{}{}", "0".repeat(2 - out.len()), out) 33 format!("{}{}", "0".repeat(2 - out.len()), out)
34} 34}
src/global/functions/update_provider.rs +25 −5
@@ -72,14 +72,33 @@ pub fn update_provider(data: &mut FrameworkData) {
72 } 72 }
73 }, 73 },
74 )], 74 )],
75 Page::SingleItem(SingleItemPage::Video(id)) => vec![ 75 Page::MainMenu(MainMenuPage::Subscriptions) => vec![(
76 String::from("url"),
77 match status.provider {
78 Provider::YouTube => String::from("https://www.youtube.com/feed/subscriptions"),
79 Provider::Invidious => {
80 format!("{}/feed/subscriptions", mainconfig.invidious_instance)
81 }
82 },
83 )],
84 Page::MainMenu(MainMenuPage::Library) => vec![(
85 String::from("url"),
86 match status.provider {
87 Provider::YouTube => String::from("https://www.youtube.com/feed/library"),
88 Provider::Invidious => {
89 format!("{}/feed/library", mainconfig.invidious_instance)
90 }
91 },
92 )],
93 Page::SingleItem(SingleItemPage::Video(id))
94 | Page::SingleItem(SingleItemPage::LocalVideo(id)) => vec![
76 ( 95 (
77 String::from("url"), 96 String::from("url"),
78 match status.provider { 97 match status.provider {
79 Provider::Invidious => { 98 Provider::Invidious => {
80 format!("{}/watch?v={}", mainconfig.invidious_instance, id) 99 format!("{}/watch?v={}", mainconfig.invidious_instance, id)
81 } 100 }
82 Provider::YouTube => format!("https://youtu.be/{}", id), 101 Provider::YouTube => format!("https://youtu.be/{id}"),
83 }, 102 },
84 ), 103 ),
85 ( 104 (
@@ -88,7 +107,7 @@ pub fn update_provider(data: &mut FrameworkData) {
88 Provider::Invidious => { 107 Provider::Invidious => {
89 format!("{}/embed/{}", mainconfig.invidious_instance, id) 108 format!("{}/embed/{}", mainconfig.invidious_instance, id)
90 } 109 }
91 Provider::YouTube => format!("https://youtube.com/embed/{}", id), 110 Provider::YouTube => format!("https://youtube.com/embed/{id}"),
92 }, 111 },
93 ), 112 ),
94 ( 113 (
@@ -108,12 +127,13 @@ pub fn update_provider(data: &mut FrameworkData) {
108 }, 127 },
109 ), 128 ),
110 ], 129 ],
111 Page::SingleItem(SingleItemPage::Playlist(id)) => vec![ 130 Page::SingleItem(SingleItemPage::Playlist(id))
131 | Page::SingleItem(SingleItemPage::LocalPlaylist(id)) => vec![
112 ( 132 (
113 String::from("url"), 133 String::from("url"),
114 match status.provider { 134 match status.provider {
115 Provider::YouTube => { 135 Provider::YouTube => {
116 format!("https://www.youtube.com/playlist?list={}", id) 136 format!("https://www.youtube.com/playlist?list={id}")
117 } 137 }
118 Provider::Invidious => { 138 Provider::Invidious => {
119 format!("{}/playlist?list={}", mainconfig.invidious_instance, id) 139 format!("{}/playlist?list={}", mainconfig.invidious_instance, id)
src/global/functions/viewcount_text.rs +1 −1
@@ -9,7 +9,7 @@ const UNITS: &[(&str, f64)] = &[
9pub fn viewcount_text(views: u64) -> String { 9pub fn viewcount_text(views: u64) -> String {
10 for unit in UNITS.iter() { 10 for unit in UNITS.iter() {
11 if unit.1 == 1_f64 { 11 if unit.1 == 1_f64 {
12 return format!("{}", views); 12 return views.to_string();
13 } else if views >= unit.1 as u64 { 13 } else if views >= unit.1 as u64 {
14 return format!("{:.2}{}", views as f64 / unit.1, unit.0); 14 return format!("{:.2}{}", views as f64 / unit.1, unit.0);
15 } 15 }
src/global/structs/item.rs +1
@@ -16,6 +16,7 @@ use super::Errors;
16/// Items are things like a single video/playlist and channel 16/// Items are things like a single video/playlist and channel
17// they are displayed by the item info widget in `iteminfo.rs` 17// they are displayed by the item info widget in `iteminfo.rs`
18#[derive(Clone, Serialize, Deserialize)] 18#[derive(Clone, Serialize, Deserialize)]
19#[serde(tag = "type", content = "data")]
19pub enum Item { 20pub enum Item {
20 // minivideos are all videos that appeared without actually clicking into the video 21 // minivideos are all videos that appeared without actually clicking into the video
21 MiniVideo(MiniVideoItem), 22 MiniVideo(MiniVideoItem),
src/global/structs/page.rs +4
@@ -54,6 +54,8 @@ pub enum MainMenuPage {
54 Trending, 54 Trending,
55 Popular, 55 Popular,
56 History, 56 History,
57 Subscriptions,
58 Library,
57} 59}
58 60
59impl Default for MainMenuPage { 61impl Default for MainMenuPage {
@@ -79,6 +81,8 @@ pub enum ChannelDisplayPageType {
79/// Different items to be displayed on a single item page 81/// Different items to be displayed on a single item page
80#[derive(Clone, PartialEq, Eq)] 82#[derive(Clone, PartialEq, Eq)]
81pub enum SingleItemPage { 83pub enum SingleItemPage {
84 LocalVideo(String),
85 LocalPlaylist(String),
82 Video(String), 86 Video(String),
83 Playlist(String), 87 Playlist(String),
84} 88}
src/global/structs/tasks.rs +2 −2
@@ -135,7 +135,7 @@ impl TaskQueue {
135 135
136 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load() 136 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
137 { 137 {
138 Message::Error(format!("{}", e)) 138 Message::Error(e.to_string())
139 } else { 139 } else {
140 Message::None 140 Message::None
141 }; 141 };
@@ -164,7 +164,7 @@ impl TaskQueue {
164 Self::render_force_clear(framework, terminal)?; 164 Self::render_force_clear(framework, terminal)?;
165 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load() 165 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
166 { 166 {
167 Message::Error(format!("{}", e)) 167 Message::Error(e.to_string())
168 } else { 168 } else {
169 Message::None 169 Message::None
170 }; 170 };
src/global/structs/watchhistory.rs +53 −11
@@ -18,10 +18,17 @@ impl Key for WatchHistory {
18impl WatchHistory { 18impl WatchHistory {
19 /// saves the current state of watch history into a file 19 /// saves the current state of watch history into a file
20 pub fn save(&self) -> Result<(), Box<dyn Error>> { 20 pub fn save(&self) -> Result<(), Box<dyn Error>> {
21 let save_string = serde_json::to_string(self)?; 21 let save_string = serde_json::to_string_pretty(
22 &self
23 .0
24 .iter()
25 .map(|item| item.id().unwrap_or_default())
26 .filter(|id| !id.is_empty())
27 .collect::<Vec<&str>>(),
28 )?;
22 let path = home_dir() 29 let path = home_dir()
23 .unwrap() 30 .unwrap()
24 .join(".local/share/youtube-tui/watch_history.json"); 31 .join(".local/share/youtube-tui/watch_history/index.json");
25 32
26 let mut file = OpenOptions::new() 33 let mut file = OpenOptions::new()
27 .write(true) 34 .write(true)
@@ -35,29 +42,48 @@ impl WatchHistory {
35 } 42 }
36 43
37 /// add an item to watch history 44 /// add an item to watch history
38 pub fn push(&mut self, item: Item, max_items: usize) { 45 pub fn push(&mut self, item: Item, max_items: usize) -> Result<(), Box<dyn Error>> {
46 let info = home_dir()
47 .unwrap()
48 .join(".local/share/youtube-tui/watch_history/info/");
49
39 // removes duplicates and place them on top (if exists) 50 // removes duplicates and place them on top (if exists)
51 let id = item.id().unwrap_or("invalid-dump");
40 if let Some(index) = self 52 if let Some(index) = self
41 .0 53 .0
42 .iter() 54 .iter()
43 .position(|item_in_iter| item_in_iter.id() == item.id()) 55 .position(|item_in_iter| item_in_iter.id().unwrap_or_default() == id)
44 { 56 {
57 let _ = fs::remove_file(info.join(format!("{id}.json")));
45 self.0.remove(index); 58 self.0.remove(index);
46 } 59 }
60 let mut file = OpenOptions::new()
61 .write(true)
62 .create(true)
63 .truncate(true)
64 .open(info.join(format!("{id}.json")))?;
65 let item_string = serde_json::to_string(&item)?;
66 file.write_all(item_string.as_bytes())?;
67
47 self.0.push(item); 68 self.0.push(item);
48 69
49 // if length of history exceeds the maximum history length, removes that oldest item 70 // if length of history exceeds the maximum history length, removes that oldest item
50 if self.0.len() > max_items { 71 if self.0.len() > max_items {
72 let _ = fs::remove_file(
73 info.join(format!("{}.json", self.0[0].id().unwrap_or("invalid-dump"))),
74 );
51 self.0.remove(0); 75 self.0.remove(0);
52 } 76 }
77
78 Ok(())
53 } 79 }
54 80
55 /// loads watch history from file 81 /// loads watch history from file
56 pub fn load() -> Self { 82 pub fn load() -> Self {
57 let path = home_dir() 83 let path = home_dir()
58 .unwrap() 84 .unwrap()
59 .join(".local/share/youtube-tui/watch_history.json"); 85 .join(".local/share/youtube-tui/watch_history/index.json");
60 let res = (|| -> Result<Self, Box<dyn Error>> { 86 let res = (|| -> Result<Vec<String>, Box<dyn Error>> {
61 let file_string = fs::read_to_string(&path)?; 87 let file_string = fs::read_to_string(&path)?;
62 let deserialized = serde_json::from_str(&file_string)?; 88 let deserialized = serde_json::from_str(&file_string)?;
63 Ok(deserialized) 89 Ok(deserialized)
@@ -66,16 +92,22 @@ impl WatchHistory {
66 // if res is err, then the file either doesn't exist of has be altered incorrectly, in 92 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
67 // which case returns Self::default() 93 // which case returns Self::default()
68 if let Ok(deserialized) = res { 94 if let Ok(deserialized) = res {
69 deserialized 95 let info = home_dir()
96 .unwrap()
97 .join(".local/share/youtube-tui/watch_history/info/");
98 Self(
99 deserialized
100 .into_iter()
101 .filter_map(|id| fs::read_to_string(info.join(format!("{id}.json"))).ok())
102 .filter_map(|file_content| serde_json::from_str(&file_content).ok())
103 .collect(),
104 )
70 } else { 105 } else {
71 // if the file does exist, back it up 106 // if the file does exist, back it up
72 // if it doesn't exist, it will throw an error but we dont care 107 // if it doesn't exist, it will throw an error but we dont care
73 let mut new_path = path.clone(); 108 let mut new_path = path.clone();
74 new_path.pop(); 109 new_path.pop();
75 new_path.push(format!( 110 new_path.push(format!("index-{}.json", chrono::offset::Local::now(),));
76 "watch_history-{}.json",
77 chrono::offset::Local::now(),
78 ));
79 let _ = fs::rename(&path, &new_path); 111 let _ = fs::rename(&path, &new_path);
80 112
81 Self::default() 113 Self::default()
@@ -114,6 +146,16 @@ impl WatchHistory {
114 cache_thumbnails_path.join(id), 146 cache_thumbnails_path.join(id),
115 history_thumbnails_path.join(id), 147 history_thumbnails_path.join(id),
116 ); 148 );
149
150 if let Ok(fullplaylist) = item.fullplaylist() {
151 fullplaylist.videos.iter().for_each(|video| {
152 let id = video.id().unwrap_or("invalid-dump");
153 let _ = fs::rename(
154 cache_thumbnails_path.join(id),
155 history_thumbnails_path.join(id),
156 );
157 })
158 }
117 }) 159 })
118 } 160 }
119} 161}
src/init.rs +5
@@ -29,6 +29,7 @@ pub fn init(
29 let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/"); 29 let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/");
30 let history_thumbnails_path = 30 let history_thumbnails_path =
31 home_dir.join(".local/share/youtube-tui/watch_history/thumbnails/"); 31 home_dir.join(".local/share/youtube-tui/watch_history/thumbnails/");
32 let history_info_path = home_dir.join(".local/share/youtube-tui/watch_history/info/");
32 33
33 if !&cache_thumbnails_path.exists() { 34 if !&cache_thumbnails_path.exists() {
34 fs::create_dir_all(&cache_thumbnails_path).unwrap(); 35 fs::create_dir_all(&cache_thumbnails_path).unwrap();
@@ -38,6 +39,10 @@ pub fn init(
38 fs::create_dir_all(&history_thumbnails_path).unwrap(); 39 fs::create_dir_all(&history_thumbnails_path).unwrap();
39 } 40 }
40 41
42 if !&history_info_path.exists() {
43 fs::create_dir_all(&history_info_path).unwrap();
44 }
45
41 // watch history init 46 // watch history init
42 WatchHistory::init_move(); 47 WatchHistory::init_move();
43 48
src/items/iteminfo.rs +3 −3
@@ -127,7 +127,7 @@ impl FrameworkItem for ItemInfo {
127 ); 127 );
128 if let Some(views) = &minivideo.views { 128 if let Some(views) = &minivideo.views {
129 out.0.push(( 129 out.0.push((
130 format!("{} views", views), 130 format!("{views} views"),
131 Style::default().fg(appearance.colors.item_info.viewcount), 131 Style::default().fg(appearance.colors.item_info.viewcount),
132 )); 132 ));
133 } 133 }
@@ -141,7 +141,7 @@ impl FrameworkItem for ItemInfo {
141 )); 141 ));
142 if let Some(published) = &minivideo.published { 142 if let Some(published) = &minivideo.published {
143 out.0.push(( 143 out.0.push((
144 format!("Published {}", published), 144 format!("Published {published}"),
145 Style::default().fg(appearance.colors.item_info.published), 145 Style::default().fg(appearance.colors.item_info.published),
146 )); 146 ));
147 } 147 }
@@ -365,7 +365,7 @@ impl FrameworkItem for ItemInfo {
365 if text.is_empty() { 365 if text.is_empty() {
366 return; 366 return;
367 } 367 }
368 let paragraph = Paragraph::new(format!("Description:\n{}", text)) 368 let paragraph = Paragraph::new(format!("Description:\n{text}"))
369 .style(style) 369 .style(style)
370 .wrap(Wrap { trim: true }); 370 .wrap(Wrap { trim: true });
371 frame.render_widget( 371 frame.render_widget(
src/items/itemlist.rs +74 −33
@@ -39,6 +39,10 @@ impl ItemList {
39 mainconfig: &MainConfig, 39 mainconfig: &MainConfig,
40 status: &Status, 40 status: &Status,
41 ) -> Vec<(String, String)> { 41 ) -> Vec<(String, String)> {
42 if self.textlist.items.is_empty() {
43 return vec![];
44 }
45
42 match &self.items[self.textlist.selected] { 46 match &self.items[self.textlist.selected] {
43 Item::MiniVideo(MiniVideoItem { id, .. }) 47 Item::MiniVideo(MiniVideoItem { id, .. })
44 | Item::FullVideo(FullVideoItem { id, .. }) => { 48 | Item::FullVideo(FullVideoItem { id, .. }) => {
@@ -121,41 +125,76 @@ impl ItemList {
121 125
122 /// handles select (enter) 126 /// handles select (enter)
123 fn select_at_cursor(&self, framework: &mut FrameworkClean) { 127 fn select_at_cursor(&self, framework: &mut FrameworkClean) {
124 let page_to_load = match &self.items[self.textlist.selected] { 128 let page = framework.data.state.get::<Page>().unwrap();
125 Item::MiniVideo(MiniVideoItem { id, .. }) 129 let page_to_load = if *page == Page::MainMenu(MainMenuPage::History) {
126 | Item::FullVideo(FullVideoItem { id, .. }) => { 130 match &self.items[self.textlist.selected] {
127 Some(Page::SingleItem(SingleItemPage::Video(id.clone()))) 131 Item::MiniVideo(MiniVideoItem { id, .. })
128 } 132 | Item::FullVideo(FullVideoItem { id, .. }) => {
129 Item::MiniPlaylist(MiniPlaylistItem { id, .. }) 133 Some(Page::SingleItem(SingleItemPage::LocalVideo(id.clone())))
130 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => { 134 }
131 Some(Page::SingleItem(SingleItemPage::Playlist(id.clone()))) 135 Item::MiniPlaylist(MiniPlaylistItem { id, .. })
132 } 136 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
133 Item::MiniChannel(MiniChannelItem { id, .. }) 137 Some(Page::SingleItem(SingleItemPage::LocalPlaylist(id.clone())))
134 | Item::FullChannel(FullChannelItem { id, .. }) => { 138 }
135 Some(Page::ChannelDisplay(ChannelDisplayPage { 139 Item::MiniChannel(MiniChannelItem { id: _id, .. })
136 id: id.clone(), 140 | Item::FullChannel(FullChannelItem { id: _id, .. }) => todo!(),
137 r#type: ChannelDisplayPageType::Main, 141 Item::Unknown(_) => {
138 })) 142 *framework.data.global.get_mut::<Message>().unwrap() =
143 Message::Message(String::from("Unknown item"));
144 framework
145 .data
146 .state
147 .get_mut::<Tasks>()
148 .unwrap()
149 .priority
150 .push(Task::RenderAll);
151 None
152 }
153 Item::Page(b) => match framework.data.state.get::<Page>().unwrap() {
154 Page::Search(search) => Some(Page::Search(Search {
155 page: if *b { search.page + 1 } else { search.page - 1 },
156 ..search.clone()
157 })),
158 _ => unreachable!("Page turners can only be used in search pages"),
159 },
139 } 160 }
140 Item::Unknown(_) => { 161 } else {
141 *framework.data.global.get_mut::<Message>().unwrap() = 162 match &self.items[self.textlist.selected] {
142 Message::Message(String::from("Unknown item")); 163 Item::MiniVideo(MiniVideoItem { id, .. })
143 framework 164 | Item::FullVideo(FullVideoItem { id, .. }) => {
144 .data 165 Some(Page::SingleItem(SingleItemPage::Video(id.clone())))
145 .state 166 }
146 .get_mut::<Tasks>() 167 Item::MiniPlaylist(MiniPlaylistItem { id, .. })
147 .unwrap() 168 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
148 .priority 169 Some(Page::SingleItem(SingleItemPage::Playlist(id.clone())))
149 .push(Task::RenderAll); 170 }
150 None 171 Item::MiniChannel(MiniChannelItem { id, .. })
172 | Item::FullChannel(FullChannelItem { id, .. }) => {
173 Some(Page::ChannelDisplay(ChannelDisplayPage {
174 id: id.clone(),
175 r#type: ChannelDisplayPageType::Main,
176 }))
177 }
178 Item::Unknown(_) => {
179 *framework.data.global.get_mut::<Message>().unwrap() =
180 Message::Message(String::from("Unknown item"));
181 framework
182 .data
183 .state
184 .get_mut::<Tasks>()
185 .unwrap()
186 .priority
187 .push(Task::RenderAll);
188 None
189 }
190 Item::Page(b) => match framework.data.state.get::<Page>().unwrap() {
191 Page::Search(search) => Some(Page::Search(Search {
192 page: if *b { search.page + 1 } else { search.page - 1 },
193 ..search.clone()
194 })),
195 _ => unreachable!("Page turners can only be used in search pages"),
196 },
151 } 197 }
152 Item::Page(b) => match framework.data.state.get::<Page>().unwrap() {
153 Page::Search(search) => Some(Page::Search(Search {
154 page: if *b { search.page + 1 } else { search.page - 1 },
155 ..search.clone()
156 })),
157 _ => unreachable!("Page turners can only be used in search pages"),
158 },
159 }; 198 };
160 199
161 if let Some(page_to_load) = page_to_load { 200 if let Some(page_to_load) = page_to_load {
@@ -272,6 +311,8 @@ impl FrameworkItem for ItemList {
272 .map(|item| Item::from_popular_item(item, image_index)) 311 .map(|item| Item::from_popular_item(item, image_index))
273 .collect(); 312 .collect();
274 } 313 }
314 Page::MainMenu(MainMenuPage::Subscriptions) => {}
315 Page::MainMenu(MainMenuPage::Library) => {}
275 Page::MainMenu(MainMenuPage::History) => { 316 Page::MainMenu(MainMenuPage::History) => {
276 // the vector needs to be reversed because the latest watch history is pushed to 317 // the vector needs to be reversed because the latest watch history is pushed to
277 // the back, meaning it needs to be reversed so that the latests one are on top 318 // the back, meaning it needs to be reversed so that the latests one are on top
src/items/pagebutton.rs +54 −12
@@ -12,14 +12,16 @@ use tui::{
12use tui_additions::framework::FrameworkItem; 12use tui_additions::framework::FrameworkItem;
13 13
14/// button that on press will go to another page instead of selecting it 14/// button that on press will go to another page instead of selecting it
15#[derive(Clone, Copy)] 15#[derive(Clone, Copy, PartialEq, Eq)]
16pub enum PageButton { 16pub enum PageButton {
17 Trending, 17 Trending,
18 Popular, 18 Popular,
19 History,
20 ChannelMain, 19 ChannelMain,
21 ChannelVideos, 20 ChannelVideos,
22 ChannelPlaylists, 21 ChannelPlaylists,
22 History,
23 Subscriptions,
24 Library,
23} 25}
24 26
25impl PageButton { 27impl PageButton {
@@ -27,7 +29,6 @@ impl PageButton {
27 match self { 29 match self {
28 Self::Trending => Page::MainMenu(MainMenuPage::Trending), 30 Self::Trending => Page::MainMenu(MainMenuPage::Trending),
29 Self::Popular => Page::MainMenu(MainMenuPage::Popular), 31 Self::Popular => Page::MainMenu(MainMenuPage::Popular),
30 Self::History => Page::MainMenu(MainMenuPage::History),
31 Self::ChannelMain => Page::ChannelDisplay(ChannelDisplayPage { 32 Self::ChannelMain => Page::ChannelDisplay(ChannelDisplayPage {
32 id: current_page.channeldisplay().id.clone(), 33 id: current_page.channeldisplay().id.clone(),
33 r#type: ChannelDisplayPageType::Main, 34 r#type: ChannelDisplayPageType::Main,
@@ -40,6 +41,25 @@ impl PageButton {
40 id: current_page.channeldisplay().id.clone(), 41 id: current_page.channeldisplay().id.clone(),
41 r#type: ChannelDisplayPageType::Playlists, 42 r#type: ChannelDisplayPageType::Playlists,
42 }), 43 }),
44 Self::History => Page::MainMenu(MainMenuPage::History),
45 Self::Subscriptions => Page::MainMenu(MainMenuPage::Subscriptions),
46 Self::Library => Page::MainMenu(MainMenuPage::Library),
47 }
48 }
49
50 fn update_toggleable(&mut self, page: &Page) {
51 if *self == Self::Popular || *self == Self::Trending {
52 match page {
53 Page::MainMenu(MainMenuPage::Popular) => *self = Self::Popular,
54 Page::MainMenu(MainMenuPage::Trending) => *self = Self::Trending,
55 _ => {}
56 }
57 } else if *self == Self::Subscriptions || *self == Self::Library {
58 match page {
59 Page::MainMenu(MainMenuPage::Subscriptions) => *self = Self::Subscriptions,
60 Page::MainMenu(MainMenuPage::Library) => *self = Self::Library,
61 _ => {}
62 }
43 } 63 }
44 } 64 }
45} 65}
@@ -49,15 +69,25 @@ impl ToString for PageButton {
49 match self { 69 match self {
50 Self::Popular => String::from("Popular"), 70 Self::Popular => String::from("Popular"),
51 Self::Trending => String::from("Trending"), 71 Self::Trending => String::from("Trending"),
52 Self::History => String::from("History"),
53 Self::ChannelMain => String::from("Main"), 72 Self::ChannelMain => String::from("Main"),
54 Self::ChannelVideos => String::from("Videos"), 73 Self::ChannelVideos => String::from("Videos"),
55 Self::ChannelPlaylists => String::from("Playlists"), 74 Self::ChannelPlaylists => String::from("Playlists"),
75 Self::History => String::from("History"),
76 Self::Subscriptions => String::from("Subscriptions"),
77 Self::Library => String::from("Library"),
56 } 78 }
57 } 79 }
58} 80}
59 81
60impl FrameworkItem for PageButton { 82impl FrameworkItem for PageButton {
83 fn load_item(
84 &mut self,
85 framework: &mut tui_additions::framework::FrameworkClean,
86 _info: tui_additions::framework::ItemInfo,
87 ) -> Result<(), Box<dyn std::error::Error>> {
88 self.update_toggleable(framework.data.state.get::<Page>().unwrap());
89 Ok(())
90 }
61 // it is basically a paragraph (text) with borders 91 // it is basically a paragraph (text) with borders
62 fn render( 92 fn render(
63 &mut self, 93 &mut self,
@@ -94,18 +124,30 @@ impl FrameworkItem for PageButton {
94 124
95 // when selected creates a load page task, but returns false to show that it is not being selected 125 // when selected creates a load page task, but returns false to show that it is not being selected
96 fn select(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool { 126 fn select(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool {
97 let current_page = framework.data.state.get::<Page>().unwrap().clone(); 127 let current_page = framework.data.state.get::<Page>().unwrap();
128 let self_page = self.page(current_page);
98 129
99 if self.page(&current_page) == current_page { 130 if self_page == *current_page {
100 *framework.data.global.get_mut::<Message>().unwrap() = 131 match self {
101 Message::Message(String::from("You are already on this page")); 132 Self::Trending => *self = Self::Popular,
102 return false; 133 Self::Popular => *self = Self::Trending,
134 Self::Subscriptions => *self = Self::Library,
135 Self::Library => *self = Self::Subscriptions,
136 _ => {
137 *framework.data.global.get_mut::<Message>().unwrap() =
138 Message::Message(String::from("You are already on this page"));
139 return false;
140 }
141 }
103 } 142 }
104 143
105 let tasks = framework.data.state.get_mut::<Tasks>().unwrap(); 144 framework
106 tasks 145 .data
146 .state
147 .get_mut::<Tasks>()
148 .unwrap()
107 .priority 149 .priority
108 .push(Task::LoadPage(self.page(&current_page))); 150 .push(Task::LoadPage(self.page(&self_page)));
109 151
110 false 152 false
111 } 153 }
src/items/singleitem.rs +73 −17
@@ -1,3 +1,5 @@
1use std::fs;
2
1use super::ItemInfo; 3use super::ItemInfo;
2use crate::{ 4use crate::{
3 config::{AppearanceConfig, CommandsConfig, KeyBindingsConfig, MainConfig, Provider}, 5 config::{AppearanceConfig, CommandsConfig, KeyBindingsConfig, MainConfig, Provider},
@@ -9,6 +11,7 @@ use crate::{
9 }, 11 },
10 }, 12 },
11}; 13};
14use home::home_dir;
12use tui::{ 15use tui::{
13 layout::{Constraint, Rect}, 16 layout::{Constraint, Rect},
14 style::Style, 17 style::Style,
@@ -67,22 +70,34 @@ pub struct SinglePlaylistItem {
67 70
68impl SingleVideoItem { 71impl SingleVideoItem {
69 pub fn new(commands: &CommandsConfig) -> Self { 72 pub fn new(commands: &CommandsConfig) -> Self {
73 Self::new_with_map(commands
74 .video
75 .clone()
76 .into_iter()
77 .map(|(display, command)| (display, command))
78 .collect())
79 }
80
81 pub fn new_local(commands: &CommandsConfig) -> Self {
82 Self::new_with_map(commands
83 .local_video
84 .clone()
85 .into_iter()
86 .map(|(display, command)| (display, command))
87 .collect())
88 }
89
90 pub fn new_with_map(commands: Vec<(String, String)>) -> Self {
70 Self { 91 Self {
71 textlist: TextList::default() 92 textlist: TextList::default()
72 .items( 93 .items(
73 &commands 94 &commands
74 .video
75 .iter() 95 .iter()
76 .map(|command| &command.0) 96 .map(|command| &command.0)
77 .collect::<Vec<_>>(), 97 .collect::<Vec<_>>(),
78 ) 98 )
79 .unwrap(), 99 .unwrap(),
80 commands: commands 100 commands,
81 .video
82 .clone()
83 .into_iter()
84 .map(|(display, command)| (display, command))
85 .collect(),
86 } 101 }
87 } 102 }
88 103
@@ -167,16 +182,34 @@ impl SingleVideoItem {
167 182
168impl SinglePlaylistItem { 183impl SinglePlaylistItem {
169 pub fn new(commands: &CommandsConfig, playlist_items: &[Item]) -> Self { 184 pub fn new(commands: &CommandsConfig, playlist_items: &[Item]) -> Self {
185 Self::new_with_map(commands
186 .playlist
187 .clone()
188 .into_iter()
189 .map(|(display, command)| (display, command))
190 .collect(), playlist_items)
191 }
192
193 pub fn new_local(commands: &CommandsConfig, playlist_items: &[Item]) -> Self {
194 Self::new_with_map(commands
195 .local_playlist
196 .clone()
197 .into_iter()
198 .map(|(display, command)| (display, command))
199 .collect(), playlist_items)
200 }
201
202 pub fn new_with_map(commands: Vec<(String, String)>, playlist_items: &[Item]) -> Self {
170 let hovered_video = ItemInfo::new(if playlist_items.is_empty() { 203 let hovered_video = ItemInfo::new(if playlist_items.is_empty() {
171 None 204 None
172 } else { 205 } else {
173 Some(playlist_items[0].clone()) 206 Some(playlist_items[0].clone())
174 }); 207 });
208
175 Self { 209 Self {
176 commands_view: TextList::default() 210 commands_view: TextList::default()
177 .items( 211 .items(
178 &commands 212 &commands
179 .playlist
180 .iter() 213 .iter()
181 .map(|command| &command.0) 214 .map(|command| &command.0)
182 .collect::<Vec<_>>(), 215 .collect::<Vec<_>>(),
@@ -193,12 +226,7 @@ impl SinglePlaylistItem {
193 items 226 items
194 }) 227 })
195 .unwrap(), 228 .unwrap(),
196 commands: commands 229 commands,
197 .playlist
198 .clone()
199 .into_iter()
200 .map(|(display, command)| (display, command))
201 .collect(),
202 hovered_video, 230 hovered_video,
203 is_commands_view: true, 231 is_commands_view: true,
204 } 232 }
@@ -592,13 +620,12 @@ impl FrameworkItem for SingleItem {
592 unreachable!("item `SingleItem` cannot be used in {page:?}") 620 unreachable!("item `SingleItem` cannot be used in {page:?}")
593 }; 621 };
594 622
595 let client = &framework.data.global.get::<InvidiousClient>().unwrap().0;
596
597 let mainconfig = framework.data.global.get::<MainConfig>().unwrap(); 623 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
598 // load items using the invidious api 624 // load items using the invidious api
599 // gets the item that it needs to load from `data.state.Page` 625 // gets the item that it needs to load from `data.state.Page`
600 self.item = match r#type { 626 self.item = match r#type {
601 SingleItemPage::Video(id) => { 627 SingleItemPage::Video(id) => {
628 let client = &framework.data.global.get::<InvidiousClient>().unwrap().0;
602 self.r#type = SingleItemType::Video(SingleVideoItem::new( 629 self.r#type = SingleItemType::Video(SingleVideoItem::new(
603 framework.data.global.get::<CommandsConfig>().unwrap(), 630 framework.data.global.get::<CommandsConfig>().unwrap(),
604 )); 631 ));
@@ -609,6 +636,7 @@ impl FrameworkItem for SingleItem {
609 Some(video) 636 Some(video)
610 } 637 }
611 SingleItemPage::Playlist(id) => { 638 SingleItemPage::Playlist(id) => {
639 let client = &framework.data.global.get::<InvidiousClient>().unwrap().0;
612 let playlist = 640 let playlist =
613 Item::from_full_playlist(client.playlist(id, None)?, mainconfig.image_index); 641 Item::from_full_playlist(client.playlist(id, None)?, mainconfig.image_index);
614 let videos = &playlist.fullplaylist()?.videos; 642 let videos = &playlist.fullplaylist()?.videos;
@@ -628,6 +656,34 @@ impl FrameworkItem for SingleItem {
628 }); 656 });
629 } 657 }
630 658
659 Some(playlist)
660 }
661 SingleItemPage::LocalVideo(id) => {
662 let s = fs::read_to_string(home_dir().unwrap().join(format!(
663 ".local/share/youtube-tui/watch_history/info/{id}.json"
664 )))?;
665 self.r#type = SingleItemType::Video(SingleVideoItem::new_local(
666 framework.data.global.get::<CommandsConfig>().unwrap(),
667 ));
668
669 Some(serde_json::from_str(&s)?)
670 }
671
672 SingleItemPage::LocalPlaylist(id) => {
673 let s = fs::read_to_string(home_dir().unwrap().join(format!(
674 ".local/share/youtube-tui/watch_history/info/{id}.json"
675 )))?;
676
677 let playlist: Item = serde_json::from_str(&s)?;
678 let videos = &playlist.fullplaylist()?.videos;
679 self.r#type = SingleItemType::Playlist(
680 SinglePlaylistItem::new_local(
681 framework.data.global.get::<CommandsConfig>().unwrap(),
682 videos,
683 )
684 .into(),
685 );
686
631 Some(playlist) 687 Some(playlist)
632 } 688 }
633 }; 689 };
@@ -648,7 +704,7 @@ impl FrameworkItem for SingleItem {
648 704
649 // push to watch history 705 // push to watch history
650 let watch_history = framework.data.global.get_mut::<WatchHistory>().unwrap(); 706 let watch_history = framework.data.global.get_mut::<WatchHistory>().unwrap();
651 watch_history.push(item, max_watch_history); 707 watch_history.push(item, max_watch_history)?;
652 watch_history.save()?; 708 watch_history.save()?;
653 } 709 }
654 710
src/run.rs +2 −2
@@ -152,7 +152,7 @@ pub fn run(
152 if framework.is_selected() { 152 if framework.is_selected() {
153 if let Err(e) = framework.key_input(key) { 153 if let Err(e) = framework.key_input(key) {
154 *framework.data.global.get_mut::<Message>().unwrap() = 154 *framework.data.global.get_mut::<Message>().unwrap() =
155 Message::Error(format!("{}", e)); 155 Message::Error(e.to_string());
156 }; 156 };
157 continue; 157 continue;
158 } 158 }
@@ -217,7 +217,6 @@ pub fn run(
217 let status = framework.data.global.get_mut::<Status>().unwrap(); 217 let status = framework.data.global.get_mut::<Status>().unwrap();
218 status.render_image = true; 218 status.render_image = true;
219 219
220 update_provider(&mut framework.data);
221 framework 220 framework
222 .data 221 .data
223 .state 222 .state
@@ -228,6 +227,7 @@ pub fn run(
228 let state_envs = 227 let state_envs =
229 framework.data.state.get_mut::<StateEnvs>().unwrap(); 228 framework.data.state.get_mut::<StateEnvs>().unwrap();
230 set_envs(state_envs.clone().0.into_iter(), &mut state_envs.0); 229 set_envs(state_envs.clone().0.into_iter(), &mut state_envs.0);
230 update_provider(&mut framework.data);
231 } 231 }
232 } 232 }
233 KeyAction::FirstHistory => { 233 KeyAction::FirstHistory => {