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 = [
19231923
19241924[[package]]
19251925name = "youtube-tui"
1926version = "0.6.2"
1926version = "0.7.0"
19271927dependencies = [
19281928 "chrono",
19291929 "clipboard",
Cargo.toml +1 −1
@@ -1,6 +1,6 @@
11[package]
22name = "youtube-tui"
3version = "0.6.2"
3version = "0.7.0"
44authors = ["Siriusmart <siriusmart@tuta.io>"]
55edition = "2021"
66description = "An aesthetically pleasing YouTube TUI written in Rust"
src/config/commandbindings.rs +26 −2
@@ -22,6 +22,8 @@ pub struct CommandBindings {
2222 pub channel_videos: HashMap<KeyCode, HashMap<u8, String>>,
2323 pub channel_playlists: HashMap<KeyCode, HashMap<u8, String>>,
2424 pub watchhistory: HashMap<KeyCode, HashMap<u8, String>>,
25 pub subscriptions: HashMap<KeyCode, HashMap<u8, String>>,
26 pub libray: HashMap<KeyCode, HashMap<u8, String>>,
2527}
2628
2729impl Key for CommandBindings {
@@ -41,8 +43,14 @@ impl CommandBindings {
4143 Page::MainMenu(MainMenuPage::Trending) => get_command(key, &self.trending),
4244 Page::MainMenu(MainMenuPage::Popular) => get_command(key, &self.popular),
4345 Page::MainMenu(MainMenuPage::History) => get_command(key, &self.watchhistory),
44 Page::SingleItem(SingleItemPage::Video(_)) => get_command(key, &self.video),
45 Page::SingleItem(SingleItemPage::Playlist(_)) => get_command(key, &self.playlist),
46 Page::MainMenu(MainMenuPage::Subscriptions) => get_command(key, &self.subscriptions),
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 }
4654 Page::ChannelDisplay(ChannelDisplayPage {
4755 r#type: ChannelDisplayPageType::Main,
4856 ..
@@ -90,6 +98,10 @@ pub struct CommandBindingsSerde {
9098 pub channel_playlists: HashMap<KeyCodeSerde, HashMap<u8, String>>,
9199 #[serde(default = "watchhistory_default")]
92100 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>>,
93105}
94106
95107impl ConfigTrait for CommandBindingsSerde {
@@ -109,6 +121,8 @@ impl CommandBindingsSerde {
109121 video: de_serde(self.video)?,
110122 trending: de_serde(self.trending)?,
111123 watchhistory: de_serde(self.watchhistory)?,
124 subscriptions: de_serde(self.subscriptions)?,
125 libray: de_serde(self.library)?,
112126 })
113127 }
114128}
@@ -126,6 +140,8 @@ impl Default for CommandBindingsSerde {
126140 video: video_default(),
127141 trending: trending_default(),
128142 watchhistory: watchhistory_default(),
143 subscriptions: subscriptions_default(),
144 library: library_default(),
129145 }
130146 }
131147}
@@ -228,3 +244,11 @@ fn watchhistory_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
228244 (KeyCodeSerde::Char('p'), HashMap::from([(2, String::from("run mpv '${hover-url}'"))]))
229245 ])
230246}
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 {
1111 pub launch_command: String,
1212 pub video: Vec<(String, String)>,
1313 pub playlist: Vec<(String, String)>,
14 pub local_video: Vec<(String, String)>,
15 pub local_playlist: Vec<(String, String)>,
1416}
1517
1618impl Key for CommandsConfig {
@@ -31,6 +33,16 @@ impl From<CommandsConfigSerde> for CommandsConfig {
3133 .into_iter()
3234 .map(|hashmap| hashmap.into_iter().last().unwrap())
3335 .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(),
3446 }
3547 }
3648}
@@ -45,6 +57,10 @@ pub struct CommandsConfigSerde {
4557 pub video: Vec<HashMap<String, String>>,
4658 #[serde(default = "playlist_default")]
4759 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>>,
4864}
4965
5066impl ConfigTrait for CommandsConfigSerde {
@@ -57,6 +73,8 @@ impl Default for CommandsConfigSerde {
5773 launch_command: launch_command_default(),
5874 video: video_default(),
5975 playlist: playlist_default(),
76 local_video: local_video_default(),
77 local_playlist: local_playlist_default(),
6078 }
6179 }
6280}
@@ -152,3 +170,96 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
152170 )]),
153171 ]
154172}
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 {
169169 Popular,
170170 /// the history button which loads the watch history page
171171 History,
172 /// the subscriptions button which loads the subscriptions page
173 Subscriptions,
174 /// the library button which loads the saved page
175 Library,
172176 /// the search filters `...` button, displays a popup when selected
173177 SearchFilters,
174178 /// playlist and video info display
@@ -191,6 +195,8 @@ impl PageItems {
191195 Self::Popular => Box::new(PageButton::Popular),
192196 Self::Trending => Box::new(PageButton::Trending),
193197 Self::History => Box::new(PageButton::History),
198 Self::Subscriptions => Box::new(PageButton::Subscriptions),
199 Self::Library => Box::new(PageButton::Library),
194200 Self::MessageBar => Box::<MessageBar>::default(),
195201 Self::ItemList => Box::<ItemList>::default(),
196202 Self::SearchFilters => Box::<SearchFilter>::default(),
@@ -207,6 +213,8 @@ impl PageItems {
207213 Self::Popular
208214 | Self::Trending
209215 | Self::History
216 | Self::Subscriptions
217 | Self::Library
210218 | Self::ChannelMain
211219 | Self::ChannelVideos
212220 | Self::ChannelPlaylists => Constraint::Length(15),
@@ -221,6 +229,8 @@ impl PageItems {
221229 match self {
222230 Self::Popular
223231 | Self::History
232 | Self::Subscriptions
233 | Self::Library
224234 | Self::ChannelMain
225235 | Self::ChannelVideos
226236 | Self::ChannelPlaylists
@@ -262,7 +272,7 @@ fn main_menu_default() -> PageConfig {
262272 layout: vec![
263273 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
264274 PageRow::from_vec(
265 vec![PageItems::Popular, PageItems::Trending, PageItems::History],
275 vec![PageItems::Popular, PageItems::Library, PageItems::History],
266276 true,
267277 ),
268278 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> {
1111 // contained a channel id
1212 if identifier.len() < index + 33 {
1313 return Err(format!(
14 "Cannot find channel id from string `{}`",
15 identifier
14 "Cannot find channel id from string `{identifier}`"
1615 ));
1716 }
1817 index + 9
1918 } else {
2019 return Err(format!(
21 "Cannot find channel id from string `{}`",
22 identifier
20 "Cannot find channel id from string `{identifier}`"
2321 ));
2422 };
2523
@@ -36,17 +34,17 @@ pub fn from_video_url(identifier: &str) -> Result<String, String> {
3634 // the id can come after "?v=" in an url
3735 let index = if let Some(index) = identifier.find("?v=") {
3836 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}`"));
4038 }
4139 index + 3
4240 // and also "youtu.be/"
4341 } else if let Some(index) = identifier.find("youtu.be/") {
4442 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}`"));
4644 }
4745 index + 9
4846 } else {
49 return Err(format!("Cannot find video id from string `{}`", identifier));
47 return Err(format!("Cannot find video id from string `{identifier}`"));
5048 };
5149
5250 Ok(identifier[index..index + 11].to_string())
@@ -63,15 +61,13 @@ pub fn from_playlist_url(identifier: &str) -> Result<String, String> {
6361 let index = if let Some(index) = identifier.find("list=") {
6462 if identifier.len() < index + 39 {
6563 return Err(format!(
66 "Cannot find plalyist id from string `{}`",
67 identifier
64 "Cannot find plalyist id from string `{identifier}`"
6865 ));
6966 }
7067 index + 5
7168 } else {
7269 return Err(format!(
73 "Cannot find playlist id from string `{}`",
74 identifier
70 "Cannot find playlist id from string `{identifier}`"
7571 ));
7672 };
7773
src/global/functions/run_command.rs +10
@@ -83,6 +83,8 @@ pub fn run_single_command(
8383 "popular" => Some(Page::MainMenu(MainMenuPage::Popular)),
8484 "trending" => Some(Page::MainMenu(MainMenuPage::Trending)),
8585 "watchhistory" => Some(Page::MainMenu(MainMenuPage::History)),
86 "subscriptions" => Some(Page::MainMenu(MainMenuPage::Subscriptions)),
87 "library" => Some(Page::MainMenu(MainMenuPage::Library)),
8688 "channel" => {
8789 if command.len() == 2 {
8890 *framework.data.global.get_mut::<Message>().unwrap() =
@@ -169,6 +171,11 @@ pub fn run_single_command(
169171 ["popular"] => run_single_command(&["loadpage", "popular"], framework, terminal),
170172 ["trending"] => run_single_command(&["loadpage", "trending"], framework, terminal),
171173 ["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),
172179 ["search"] => run_single_command(&["loadpage", "search"], framework, terminal),
173180 ["search", ..] => run_single_command(
174181 &format!("loadpage search {}", command[1..].join(" "))
@@ -334,6 +341,9 @@ const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
334341 \x1b[33mloadpage popular\x1b[0m Loads the popular videos page
335342 \x1b[33mloadpage trending\x1b[0m Loads the trending videos page
336343 \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
337347 \x1b[33mloadpage search [query]\x1b[0m Loads the search page with the given query
338348 \x1b[33mloadpage video [identifier]\x1b[0m Loads the video item page
339349 \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 {
88 if secs >= SECS_IN_HOUR {
99 let hours = secs / SECS_IN_HOUR;
1010 secs -= hours * SECS_IN_HOUR;
11 out.push(format!("{}", hours));
11 out.push(hours.to_string());
1212 }
1313
1414 if secs >= SECS_IN_MINUTE {
@@ -28,7 +28,7 @@ pub fn secs_display_string(mut secs: u32) -> String {
2828}
2929
3030fn two_digit_num(num: u32) -> String {
31 let out = format!("{}", num);
31 let out = num.to_string();
3232
3333 format!("{}{}", "0".repeat(2 - out.len()), out)
3434}
src/global/functions/update_provider.rs +25 −5
@@ -72,14 +72,33 @@ pub fn update_provider(data: &mut FrameworkData) {
7272 }
7373 },
7474 )],
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![
7695 (
7796 String::from("url"),
7897 match status.provider {
7998 Provider::Invidious => {
8099 format!("{}/watch?v={}", mainconfig.invidious_instance, id)
81100 }
82 Provider::YouTube => format!("https://youtu.be/{}", id),
101 Provider::YouTube => format!("https://youtu.be/{id}"),
83102 },
84103 ),
85104 (
@@ -88,7 +107,7 @@ pub fn update_provider(data: &mut FrameworkData) {
88107 Provider::Invidious => {
89108 format!("{}/embed/{}", mainconfig.invidious_instance, id)
90109 }
91 Provider::YouTube => format!("https://youtube.com/embed/{}", id),
110 Provider::YouTube => format!("https://youtube.com/embed/{id}"),
92111 },
93112 ),
94113 (
@@ -108,12 +127,13 @@ pub fn update_provider(data: &mut FrameworkData) {
108127 },
109128 ),
110129 ],
111 Page::SingleItem(SingleItemPage::Playlist(id)) => vec![
130 Page::SingleItem(SingleItemPage::Playlist(id))
131 | Page::SingleItem(SingleItemPage::LocalPlaylist(id)) => vec![
112132 (
113133 String::from("url"),
114134 match status.provider {
115135 Provider::YouTube => {
116 format!("https://www.youtube.com/playlist?list={}", id)
136 format!("https://www.youtube.com/playlist?list={id}")
117137 }
118138 Provider::Invidious => {
119139 format!("{}/playlist?list={}", mainconfig.invidious_instance, id)
src/global/functions/viewcount_text.rs +1 −1
@@ -9,7 +9,7 @@ const UNITS: &[(&str, f64)] = &[
99pub fn viewcount_text(views: u64) -> String {
1010 for unit in UNITS.iter() {
1111 if unit.1 == 1_f64 {
12 return format!("{}", views);
12 return views.to_string();
1313 } else if views >= unit.1 as u64 {
1414 return format!("{:.2}{}", views as f64 / unit.1, unit.0);
1515 }
src/global/structs/item.rs +1
@@ -16,6 +16,7 @@ use super::Errors;
1616/// Items are things like a single video/playlist and channel
1717// they are displayed by the item info widget in `iteminfo.rs`
1818#[derive(Clone, Serialize, Deserialize)]
19#[serde(tag = "type", content = "data")]
1920pub enum Item {
2021 // minivideos are all videos that appeared without actually clicking into the video
2122 MiniVideo(MiniVideoItem),
src/global/structs/page.rs +4
@@ -54,6 +54,8 @@ pub enum MainMenuPage {
5454 Trending,
5555 Popular,
5656 History,
57 Subscriptions,
58 Library,
5759}
5860
5961impl Default for MainMenuPage {
@@ -79,6 +81,8 @@ pub enum ChannelDisplayPageType {
7981/// Different items to be displayed on a single item page
8082#[derive(Clone, PartialEq, Eq)]
8183pub enum SingleItemPage {
84 LocalVideo(String),
85 LocalPlaylist(String),
8286 Video(String),
8387 Playlist(String),
8488}
src/global/structs/tasks.rs +2 −2
@@ -135,7 +135,7 @@ impl TaskQueue {
135135
136136 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
137137 {
138 Message::Error(format!("{}", e))
138 Message::Error(e.to_string())
139139 } else {
140140 Message::None
141141 };
@@ -164,7 +164,7 @@ impl TaskQueue {
164164 Self::render_force_clear(framework, terminal)?;
165165 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
166166 {
167 Message::Error(format!("{}", e))
167 Message::Error(e.to_string())
168168 } else {
169169 Message::None
170170 };
src/global/structs/watchhistory.rs +53 −11
@@ -18,10 +18,17 @@ impl Key for WatchHistory {
1818impl WatchHistory {
1919 /// saves the current state of watch history into a file
2020 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 )?;
2229 let path = home_dir()
2330 .unwrap()
24 .join(".local/share/youtube-tui/watch_history.json");
31 .join(".local/share/youtube-tui/watch_history/index.json");
2532
2633 let mut file = OpenOptions::new()
2734 .write(true)
@@ -35,29 +42,48 @@ impl WatchHistory {
3542 }
3643
3744 /// 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
3950 // removes duplicates and place them on top (if exists)
51 let id = item.id().unwrap_or("invalid-dump");
4052 if let Some(index) = self
4153 .0
4254 .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)
4456 {
57 let _ = fs::remove_file(info.join(format!("{id}.json")));
4558 self.0.remove(index);
4659 }
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
4768 self.0.push(item);
4869
4970 // if length of history exceeds the maximum history length, removes that oldest item
5071 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 );
5175 self.0.remove(0);
5276 }
77
78 Ok(())
5379 }
5480
5581 /// loads watch history from file
5682 pub fn load() -> Self {
5783 let path = home_dir()
5884 .unwrap()
59 .join(".local/share/youtube-tui/watch_history.json");
60 let res = (|| -> Result<Self, Box<dyn Error>> {
85 .join(".local/share/youtube-tui/watch_history/index.json");
86 let res = (|| -> Result<Vec<String>, Box<dyn Error>> {
6187 let file_string = fs::read_to_string(&path)?;
6288 let deserialized = serde_json::from_str(&file_string)?;
6389 Ok(deserialized)
@@ -66,16 +92,22 @@ impl WatchHistory {
6692 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
6793 // which case returns Self::default()
6894 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 )
70105 } else {
71106 // if the file does exist, back it up
72107 // if it doesn't exist, it will throw an error but we dont care
73108 let mut new_path = path.clone();
74109 new_path.pop();
75 new_path.push(format!(
76 "watch_history-{}.json",
77 chrono::offset::Local::now(),
78 ));
110 new_path.push(format!("index-{}.json", chrono::offset::Local::now(),));
79111 let _ = fs::rename(&path, &new_path);
80112
81113 Self::default()
@@ -114,6 +146,16 @@ impl WatchHistory {
114146 cache_thumbnails_path.join(id),
115147 history_thumbnails_path.join(id),
116148 );
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 }
117159 })
118160 }
119161}
src/init.rs +5
@@ -29,6 +29,7 @@ pub fn init(
2929 let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/");
3030 let history_thumbnails_path =
3131 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/");
3233
3334 if !&cache_thumbnails_path.exists() {
3435 fs::create_dir_all(&cache_thumbnails_path).unwrap();
@@ -38,6 +39,10 @@ pub fn init(
3839 fs::create_dir_all(&history_thumbnails_path).unwrap();
3940 }
4041
42 if !&history_info_path.exists() {
43 fs::create_dir_all(&history_info_path).unwrap();
44 }
45
4146 // watch history init
4247 WatchHistory::init_move();
4348
src/items/iteminfo.rs +3 −3
@@ -127,7 +127,7 @@ impl FrameworkItem for ItemInfo {
127127 );
128128 if let Some(views) = &minivideo.views {
129129 out.0.push((
130 format!("{} views", views),
130 format!("{views} views"),
131131 Style::default().fg(appearance.colors.item_info.viewcount),
132132 ));
133133 }
@@ -141,7 +141,7 @@ impl FrameworkItem for ItemInfo {
141141 ));
142142 if let Some(published) = &minivideo.published {
143143 out.0.push((
144 format!("Published {}", published),
144 format!("Published {published}"),
145145 Style::default().fg(appearance.colors.item_info.published),
146146 ));
147147 }
@@ -365,7 +365,7 @@ impl FrameworkItem for ItemInfo {
365365 if text.is_empty() {
366366 return;
367367 }
368 let paragraph = Paragraph::new(format!("Description:\n{}", text))
368 let paragraph = Paragraph::new(format!("Description:\n{text}"))
369369 .style(style)
370370 .wrap(Wrap { trim: true });
371371 frame.render_widget(
src/items/itemlist.rs +74 −33
@@ -39,6 +39,10 @@ impl ItemList {
3939 mainconfig: &MainConfig,
4040 status: &Status,
4141 ) -> Vec<(String, String)> {
42 if self.textlist.items.is_empty() {
43 return vec![];
44 }
45
4246 match &self.items[self.textlist.selected] {
4347 Item::MiniVideo(MiniVideoItem { id, .. })
4448 | Item::FullVideo(FullVideoItem { id, .. }) => {
@@ -121,41 +125,76 @@ impl ItemList {
121125
122126 /// handles select (enter)
123127 fn select_at_cursor(&self, framework: &mut FrameworkClean) {
124 let page_to_load = match &self.items[self.textlist.selected] {
125 Item::MiniVideo(MiniVideoItem { id, .. })
126 | Item::FullVideo(FullVideoItem { id, .. }) => {
127 Some(Page::SingleItem(SingleItemPage::Video(id.clone())))
128 }
129 Item::MiniPlaylist(MiniPlaylistItem { id, .. })
130 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
131 Some(Page::SingleItem(SingleItemPage::Playlist(id.clone())))
132 }
133 Item::MiniChannel(MiniChannelItem { id, .. })
134 | Item::FullChannel(FullChannelItem { id, .. }) => {
135 Some(Page::ChannelDisplay(ChannelDisplayPage {
136 id: id.clone(),
137 r#type: ChannelDisplayPageType::Main,
138 }))
128 let page = framework.data.state.get::<Page>().unwrap();
129 let page_to_load = if *page == Page::MainMenu(MainMenuPage::History) {
130 match &self.items[self.textlist.selected] {
131 Item::MiniVideo(MiniVideoItem { id, .. })
132 | Item::FullVideo(FullVideoItem { id, .. }) => {
133 Some(Page::SingleItem(SingleItemPage::LocalVideo(id.clone())))
134 }
135 Item::MiniPlaylist(MiniPlaylistItem { id, .. })
136 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
137 Some(Page::SingleItem(SingleItemPage::LocalPlaylist(id.clone())))
138 }
139 Item::MiniChannel(MiniChannelItem { id: _id, .. })
140 | Item::FullChannel(FullChannelItem { id: _id, .. }) => todo!(),
141 Item::Unknown(_) => {
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 },
139160 }
140 Item::Unknown(_) => {
141 *framework.data.global.get_mut::<Message>().unwrap() =
142 Message::Message(String::from("Unknown item"));
143 framework
144 .data
145 .state
146 .get_mut::<Tasks>()
147 .unwrap()
148 .priority
149 .push(Task::RenderAll);
150 None
161 } else {
162 match &self.items[self.textlist.selected] {
163 Item::MiniVideo(MiniVideoItem { id, .. })
164 | Item::FullVideo(FullVideoItem { id, .. }) => {
165 Some(Page::SingleItem(SingleItemPage::Video(id.clone())))
166 }
167 Item::MiniPlaylist(MiniPlaylistItem { id, .. })
168 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
169 Some(Page::SingleItem(SingleItemPage::Playlist(id.clone())))
170 }
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 },
151197 }
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 },
159198 };
160199
161200 if let Some(page_to_load) = page_to_load {
@@ -272,6 +311,8 @@ impl FrameworkItem for ItemList {
272311 .map(|item| Item::from_popular_item(item, image_index))
273312 .collect();
274313 }
314 Page::MainMenu(MainMenuPage::Subscriptions) => {}
315 Page::MainMenu(MainMenuPage::Library) => {}
275316 Page::MainMenu(MainMenuPage::History) => {
276317 // the vector needs to be reversed because the latest watch history is pushed to
277318 // 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::{
1212use tui_additions::framework::FrameworkItem;
1313
1414/// button that on press will go to another page instead of selecting it
15#[derive(Clone, Copy)]
15#[derive(Clone, Copy, PartialEq, Eq)]
1616pub enum PageButton {
1717 Trending,
1818 Popular,
19 History,
2019 ChannelMain,
2120 ChannelVideos,
2221 ChannelPlaylists,
22 History,
23 Subscriptions,
24 Library,
2325}
2426
2527impl PageButton {
@@ -27,7 +29,6 @@ impl PageButton {
2729 match self {
2830 Self::Trending => Page::MainMenu(MainMenuPage::Trending),
2931 Self::Popular => Page::MainMenu(MainMenuPage::Popular),
30 Self::History => Page::MainMenu(MainMenuPage::History),
3132 Self::ChannelMain => Page::ChannelDisplay(ChannelDisplayPage {
3233 id: current_page.channeldisplay().id.clone(),
3334 r#type: ChannelDisplayPageType::Main,
@@ -40,6 +41,25 @@ impl PageButton {
4041 id: current_page.channeldisplay().id.clone(),
4142 r#type: ChannelDisplayPageType::Playlists,
4243 }),
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 }
4363 }
4464 }
4565}
@@ -49,15 +69,25 @@ impl ToString for PageButton {
4969 match self {
5070 Self::Popular => String::from("Popular"),
5171 Self::Trending => String::from("Trending"),
52 Self::History => String::from("History"),
5372 Self::ChannelMain => String::from("Main"),
5473 Self::ChannelVideos => String::from("Videos"),
5574 Self::ChannelPlaylists => String::from("Playlists"),
75 Self::History => String::from("History"),
76 Self::Subscriptions => String::from("Subscriptions"),
77 Self::Library => String::from("Library"),
5678 }
5779 }
5880}
5981
6082impl 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 }
6191 // it is basically a paragraph (text) with borders
6292 fn render(
6393 &mut self,
@@ -94,18 +124,30 @@ impl FrameworkItem for PageButton {
94124
95125 // when selected creates a load page task, but returns false to show that it is not being selected
96126 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);
98129
99 if self.page(&current_page) == current_page {
100 *framework.data.global.get_mut::<Message>().unwrap() =
101 Message::Message(String::from("You are already on this page"));
102 return false;
130 if self_page == *current_page {
131 match self {
132 Self::Trending => *self = Self::Popular,
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 }
103142 }
104143
105 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
106 tasks
144 framework
145 .data
146 .state
147 .get_mut::<Tasks>()
148 .unwrap()
107149 .priority
108 .push(Task::LoadPage(self.page(&current_page)));
150 .push(Task::LoadPage(self.page(&self_page)));
109151
110152 false
111153 }
src/items/singleitem.rs +73 −17
@@ -1,3 +1,5 @@
1use std::fs;
2
13use super::ItemInfo;
24use crate::{
35 config::{AppearanceConfig, CommandsConfig, KeyBindingsConfig, MainConfig, Provider},
@@ -9,6 +11,7 @@ use crate::{
911 },
1012 },
1113};
14use home::home_dir;
1215use tui::{
1316 layout::{Constraint, Rect},
1417 style::Style,
@@ -67,22 +70,34 @@ pub struct SinglePlaylistItem {
6770
6871impl SingleVideoItem {
6972 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 {
7091 Self {
7192 textlist: TextList::default()
7293 .items(
7394 &commands
74 .video
7595 .iter()
7696 .map(|command| &command.0)
7797 .collect::<Vec<_>>(),
7898 )
7999 .unwrap(),
80 commands: commands
81 .video
82 .clone()
83 .into_iter()
84 .map(|(display, command)| (display, command))
85 .collect(),
100 commands,
86101 }
87102 }
88103
@@ -167,16 +182,34 @@ impl SingleVideoItem {
167182
168183impl SinglePlaylistItem {
169184 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 {
170203 let hovered_video = ItemInfo::new(if playlist_items.is_empty() {
171204 None
172205 } else {
173206 Some(playlist_items[0].clone())
174207 });
208
175209 Self {
176210 commands_view: TextList::default()
177211 .items(
178212 &commands
179 .playlist
180213 .iter()
181214 .map(|command| &command.0)
182215 .collect::<Vec<_>>(),
@@ -193,12 +226,7 @@ impl SinglePlaylistItem {
193226 items
194227 })
195228 .unwrap(),
196 commands: commands
197 .playlist
198 .clone()
199 .into_iter()
200 .map(|(display, command)| (display, command))
201 .collect(),
229 commands,
202230 hovered_video,
203231 is_commands_view: true,
204232 }
@@ -592,13 +620,12 @@ impl FrameworkItem for SingleItem {
592620 unreachable!("item `SingleItem` cannot be used in {page:?}")
593621 };
594622
595 let client = &framework.data.global.get::<InvidiousClient>().unwrap().0;
596
597623 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
598624 // load items using the invidious api
599625 // gets the item that it needs to load from `data.state.Page`
600626 self.item = match r#type {
601627 SingleItemPage::Video(id) => {
628 let client = &framework.data.global.get::<InvidiousClient>().unwrap().0;
602629 self.r#type = SingleItemType::Video(SingleVideoItem::new(
603630 framework.data.global.get::<CommandsConfig>().unwrap(),
604631 ));
@@ -609,6 +636,7 @@ impl FrameworkItem for SingleItem {
609636 Some(video)
610637 }
611638 SingleItemPage::Playlist(id) => {
639 let client = &framework.data.global.get::<InvidiousClient>().unwrap().0;
612640 let playlist =
613641 Item::from_full_playlist(client.playlist(id, None)?, mainconfig.image_index);
614642 let videos = &playlist.fullplaylist()?.videos;
@@ -628,6 +656,34 @@ impl FrameworkItem for SingleItem {
628656 });
629657 }
630658
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
631687 Some(playlist)
632688 }
633689 };
@@ -648,7 +704,7 @@ impl FrameworkItem for SingleItem {
648704
649705 // push to watch history
650706 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)?;
652708 watch_history.save()?;
653709 }
654710
src/run.rs +2 −2
@@ -152,7 +152,7 @@ pub fn run(
152152 if framework.is_selected() {
153153 if let Err(e) = framework.key_input(key) {
154154 *framework.data.global.get_mut::<Message>().unwrap() =
155 Message::Error(format!("{}", e));
155 Message::Error(e.to_string());
156156 };
157157 continue;
158158 }
@@ -217,7 +217,6 @@ pub fn run(
217217 let status = framework.data.global.get_mut::<Status>().unwrap();
218218 status.render_image = true;
219219
220 update_provider(&mut framework.data);
221220 framework
222221 .data
223222 .state
@@ -228,6 +227,7 @@ pub fn run(
228227 let state_envs =
229228 framework.data.state.get_mut::<StateEnvs>().unwrap();
230229 set_envs(state_envs.clone().0.into_iter(), &mut state_envs.0);
230 update_provider(&mut framework.data);
231231 }
232232 }
233233 KeyAction::FirstHistory => {