Commit f3b1912e0d

f3b1912e0d99b46fd8c7b0be2a1606a7b087b650

parent: 3c8e0c8185

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2023-05-25 21:03 UTC

subscriptions accessiable via command + subscription view list basically done

Layout: unified · split

src/config/commandbindings.rs +1 −1
@@ -40,8 +40,8 @@ impl CommandBindings {
4040 Page::MainMenu(MainMenuPage::Trending) => get_command(key, &self.trending),
4141 Page::MainMenu(MainMenuPage::Popular) => get_command(key, &self.popular),
4242 Page::MainMenu(MainMenuPage::History) => get_command(key, &self.watchhistory),
43 Page::MainMenu(MainMenuPage::Subscriptions) => get_command(key, &self.subscriptions),
4443 Page::MainMenu(MainMenuPage::Library) => get_command(key, &self.libray),
44 Page::Subscriptions(_) => get_command(key, &self.subscriptions),
4545 Page::SingleItem(SingleItemPage::Video(_)) => get_command(key, &self.video),
4646 Page::SingleItem(SingleItemPage::Playlist(_)) => get_command(key, &self.playlist),
4747 Page::ChannelDisplay(ChannelDisplayPage {
src/config/pages.rs +36 −3
@@ -28,6 +28,8 @@ impl Key for MinDimentions {
2828pub struct PagesConfig {
2929 #[serde(default = "main_menu_default")]
3030 pub main_menu: PageConfig,
31 #[serde(default = "subscriptions_default")]
32 pub subscriptions: PageConfig,
3133 #[serde(default = "search_default")]
3234 pub search: PageConfig,
3335 #[serde(default = "singleitem_default")]
@@ -48,6 +50,7 @@ impl Default for PagesConfig {
4850 fn default() -> Self {
4951 Self {
5052 main_menu: main_menu_default(),
53 subscriptions: subscriptions_default(),
5154 search: search_default(),
5255 singleitem: singleitem_default(),
5356 channeldisplay: channeldisplay_default(),
@@ -168,6 +171,8 @@ pub enum PageItems {
168171 Subscriptions,
169172 /// the library button which loads the saved page
170173 Library,
174 /// Subscriptions list (channels)
175 ChannelList,
171176 /// the search filters `...` button, displays a popup when selected
172177 SearchFilters,
173178 /// playlist and video info display
@@ -192,6 +197,7 @@ impl PageItems {
192197 Self::History => Box::new(PageButton::History),
193198 Self::Subscriptions => Box::new(PageButton::Subscriptions),
194199 Self::Library => Box::new(PageButton::Library),
200 Self::ChannelList => Box::<ChannelList>::default(),
195201 Self::MessageBar => Box::<MessageBar>::default(),
196202 Self::ItemList => Box::<ItemList>::default(),
197203 Self::SearchFilters => Box::<SearchFilter>::default(),
@@ -215,7 +221,9 @@ impl PageItems {
215221 | Self::ChannelPlaylists => Constraint::Length(15),
216222 Self::SearchBar => Constraint::Min(16),
217223 Self::MessageBar => Constraint::Min(3),
218 Self::ItemList | Self::SingleItemInfo | Self::ChannelDisplay => Constraint::Min(9),
224 Self::ItemList | Self::SingleItemInfo | Self::ChannelDisplay | Self::ChannelList => {
225 Constraint::Min(9)
226 }
219227 Self::SearchFilters => Constraint::Length(5),
220228 }
221229 }
@@ -233,7 +241,9 @@ impl PageItems {
233241 | Self::MessageBar
234242 | Self::SearchBar
235243 | Self::SearchFilters => Constraint::Length(3),
236 Self::ItemList | Self::SingleItemInfo | Self::ChannelDisplay => Constraint::Min(6),
244 Self::ItemList | Self::SingleItemInfo | Self::ChannelDisplay | Self::ChannelList => {
245 Constraint::Min(6)
246 }
237247 }
238248 }
239249}
@@ -267,7 +277,11 @@ fn main_menu_default() -> PageConfig {
267277 layout: vec![
268278 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
269279 PageRow::from_vec(
270 vec![PageItems::Popular, PageItems::Library, PageItems::History],
280 vec![
281 PageItems::Library,
282 PageItems::Subscriptions,
283 PageItems::History,
284 ],
271285 true,
272286 ),
273287 PageRow::from_vec(vec![PageItems::ItemList], false),
@@ -317,3 +331,22 @@ fn channeldisplay_default() -> PageConfig {
317331 message: String::from("Loading channel details..."),
318332 }
319333}
334
335fn subscriptions_default() -> PageConfig {
336 PageConfig {
337 layout: vec![
338 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
339 PageRow::from_vec(
340 vec![
341 PageItems::Library,
342 PageItems::Subscriptions,
343 PageItems::History,
344 ],
345 true,
346 ),
347 PageRow::from_vec(vec![PageItems::ChannelList], false),
348 PageRow::from_vec(vec![PageItems::MessageBar], false),
349 ],
350 message: String::from("Loading subscriptions..."),
351 }
352}
src/exit.rs +14 −4
@@ -2,16 +2,26 @@ use home::home_dir;
22use std::{error::Error, fs};
33use tui_additions::framework::Framework;
44
5use crate::global::{structs::WatchHistory, traits::Collection};
5use crate::global::{structs::*, traits::Collection};
66
77/// function to run when the app ends
88// exit tasks:
99// - move thumbnails of videos in watch history to `~/.local/share/youtube-tui/watch_history/thumbnails`
1010// - remove `~/.cache`
1111pub fn exit(framework: &Framework) -> Result<(), Box<dyn Error>> {
12 if let Some(history) = framework.data.global.get::<WatchHistory>() {
13 history.exit_move()
14 }
12 framework
13 .data
14 .global
15 .get::<WatchHistory>()
16 .unwrap()
17 .exit_move();
18 framework
19 .data
20 .global
21 .get::<Subscriptions>()
22 .unwrap()
23 .exit_move();
24 framework.data.global.get::<Library>().unwrap().exit_move();
1525
1626 let home_dir = home_dir().unwrap();
1727 let cache_path = home_dir.join(".cache/youtube-tui/");
src/global/functions/mod.rs +6 −6
@@ -1,18 +1,18 @@
11//! public functions
22mod secs_display_string;
3pub use secs_display_string::secs_display_string;
3pub use secs_display_string::*;
44mod viewcount_text;
5pub use viewcount_text::viewcount_text;
5pub use viewcount_text::*;
66mod date_text;
7pub use date_text::date_text;
7pub use date_text::*;
88mod download_all_images;
9pub use download_all_images::download_all_images;
9pub use download_all_images::*;
1010mod popup_area;
11pub use popup_area::popup_area;
11pub use popup_area::*;
1212mod run_command;
1313pub use run_command::*;
1414mod command_capture;
15pub use command_capture::command_capture;
15pub use command_capture::*;
1616mod fake_rand;
1717pub use fake_rand::*;
1818#[cfg(feature = "clipboard")]
src/global/functions/run_command.rs +81 −2
@@ -124,7 +124,7 @@ pub fn run_single_command(
124124 "popular" => Some(Page::MainMenu(MainMenuPage::Popular)),
125125 "trending" => Some(Page::MainMenu(MainMenuPage::Trending)),
126126 "watchhistory" => Some(Page::MainMenu(MainMenuPage::History)),
127 "subscriptions" => Some(Page::MainMenu(MainMenuPage::Subscriptions)),
127 "subscriptions" | "subs" => Some(Page::Subscriptions(None)),
128128 "library" => Some(Page::MainMenu(MainMenuPage::Library)),
129129 "channel" => {
130130 if command.len() == 2 {
@@ -212,7 +212,7 @@ pub fn run_single_command(
212212 ["popular"] => run_single_command(&["loadpage", "popular"], framework, terminal),
213213 ["trending"] => run_single_command(&["loadpage", "trending"], framework, terminal),
214214 ["watchhistory"] => run_single_command(&["loadpage", "watchhistory"], framework, terminal),
215 ["subscriptions"] => {
215 ["subscriptions"] | ["subs"] => {
216216 run_single_command(&["loadpage", "subscriptions"], framework, terminal)
217217 }
218218 ["bookmarks"] => run_single_command(&["loadpage", "bookmarks"], framework, terminal),
@@ -345,6 +345,83 @@ pub fn run_single_command(
345345 *framework.data.global.get_mut::<Message>().unwrap() =
346346 Message::Success(String::from("Copied to clipboad"));
347347 }
348 ["sub", identifier] => {
349 let id = if identifier.len() == 24 {
350 identifier.to_string()
351 } else {
352 let splitted = identifier.split_once("/channel/");
353
354 match splitted {
355 Some((_, actual_stuff)) if actual_stuff.len() >= 24 => {
356 actual_stuff[0..24].to_string()
357 }
358 _ => {
359 *framework.data.global.get_mut::<Message>().unwrap() =
360 Message::Error(String::from("Invalid identifier: no channel ID found"));
361 return;
362 }
363 }
364 };
365
366 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
367 let image_index = mainconfig.image_index;
368 let download_thumbnails = mainconfig.images.display();
369 let client = framework
370 .data
371 .global
372 .get::<InvidiousClient>()
373 .unwrap()
374 .clone();
375
376 *framework.data.global.get_mut::<Message>().unwrap() =
377 Message::Message(String::from("Syncing..."));
378 terminal.draw(|frame| framework.render(frame)).unwrap();
379 framework.render(&mut terminal.get_frame());
380
381 let subscriptions = framework.data.global.get_mut::<Subscriptions>().unwrap();
382 match subscriptions.sync_one(&id, &client, image_index, download_thumbnails) {
383 Ok(()) => {
384 *framework.data.global.get_mut::<Message>().unwrap() =
385 Message::Success(String::from("Channel synced"));
386 }
387 Err(e) => {
388 *framework.data.global.get_mut::<Message>().unwrap() =
389 Message::Error(format!("Sync failed: {e}"));
390 }
391 };
392 }
393 ["unsub", identifier] => {
394 let id = if identifier.len() == 24 {
395 identifier.to_string()
396 } else {
397 let splitted = identifier.split_once("/channel/");
398
399 match splitted {
400 Some((_, actual_stuff)) if actual_stuff.len() >= 24 => {
401 actual_stuff[0..24].to_string()
402 }
403 _ => {
404 *framework.data.global.get_mut::<Message>().unwrap() =
405 Message::Error(String::from("Invalid identifier: no channel ID found"));
406 return;
407 }
408 }
409 };
410
411 if framework
412 .data
413 .global
414 .get_mut::<Subscriptions>()
415 .unwrap()
416 .remove_one(&id)
417 {
418 *framework.data.global.get_mut::<Message>().unwrap() =
419 Message::Success(String::from("Unsubscribed from channel"));
420 } else {
421 *framework.data.global.get_mut::<Message>().unwrap() =
422 Message::Error(String::from("Channel not found in subscriptions"));
423 }
424 }
348425 _ => {
349426 *framework.data.global.get_mut::<Message>().unwrap() =
350427 Message::Error(format!("Unknown command: `{}`", command.join(" ")));
@@ -424,6 +501,8 @@ const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
424501 \x1b[33mbookmark [id]\x1b[0m Bookmark item with ID (item must be already loaded)
425502 \x1b[33munmark [id]\x1b[0m Remove bookmark item with ID
426503 \x1b[33mtogglemark [id]\x1b[0m Toggle bookmark status
504 \x1b[33msub [id or url]\x1b[0m Add channel to subscription
505 \x1b[33munsub [id or url]\x1b[0m Remove channel from subscription
427506
428507\x1b[91mALT:\x1b[0m
429508\x1b[37malts links back to the original command\x1b[30m
src/global/functions/update_provider.rs +1 −1
@@ -66,7 +66,7 @@ pub fn update_provider(data: &mut FrameworkData) {
6666 }
6767 },
6868 )],
69 Page::MainMenu(MainMenuPage::Subscriptions) => vec![(
69 Page::Subscriptions(_) => vec![(
7070 String::from("url"),
7171 match status.provider {
7272 Provider::YouTube => String::from("https://www.youtube.com/feed/subscriptions"),
src/global/structs/item.rs +19 −1
@@ -1,4 +1,4 @@
1use crate::global::functions::*;
1use crate::global::{functions::*, traits::CollectionItem};
22use invidious::{channel::Channel, hidden::*, universal::Playlist as FullPlaylist, video::Video};
33use serde::{Deserialize, Serialize};
44use std::fmt::Display;
@@ -21,6 +21,24 @@ pub enum Item {
2121 Unknown(SearchItemTransition),
2222}
2323
24impl CollectionItem for Item {
25 fn id(&self) -> Option<&str> {
26 self.id()
27 }
28
29 fn children_ids(&self) -> Vec<&str> {
30 if let Self::FullPlaylist(playlist) = self {
31 playlist
32 .videos
33 .iter()
34 .map(|video| video.id().unwrap())
35 .collect::<Vec<_>>()
36 } else {
37 Vec::new()
38 }
39 }
40}
41
2442/// stores information of a previewed video
2543#[derive(Clone, Serialize, Deserialize)]
2644pub struct MiniVideoItem {
src/global/structs/library.rs +5 −1
@@ -11,7 +11,7 @@ impl Key for Library {
1111 type Value = Self;
1212}
1313
14impl Collection for Library {
14impl Collection<Item> for Library {
1515 const INDEX_PATH: &'static str = ".local/share/youtube-tui/library.json";
1616
1717 fn items(&self) -> &Vec<Item> {
@@ -21,4 +21,8 @@ impl Collection for Library {
2121 fn items_mut(&mut self) -> &mut Vec<Item> {
2222 &mut self.0
2323 }
24
25 fn from_items(items: Vec<Item>) -> Self {
26 Self(items)
27 }
2428}
src/global/structs/page.rs +5 −1
@@ -9,6 +9,8 @@ use typemap::Key;
99#[derive(Clone, PartialEq, Eq)]
1010pub enum Page {
1111 MainMenu(MainMenuPage),
12 // Option<new channel selected index>
13 Subscriptions(Option<usize>),
1214 Search(Search),
1315 SingleItem(SingleItemPage),
1416 ChannelDisplay(ChannelDisplayPage),
@@ -20,6 +22,7 @@ impl Debug for Page {
2022 "{}(_)",
2123 match self {
2224 Self::MainMenu(_) => "MainMenu",
25 Self::Subscriptions(_) => "Subscriptions",
2326 Self::Search(_) => "Search",
2427 Self::SingleItem(_) => "SingleItem",
2528 Self::ChannelDisplay(_) => "ChannelDisplay",
@@ -54,7 +57,6 @@ pub enum MainMenuPage {
5457 Trending,
5558 Popular,
5659 History,
57 Subscriptions,
5860 Library,
5961}
6062
@@ -90,6 +92,7 @@ impl Page {
9092 let pages_config = framework.data.global.get::<PagesConfig>().unwrap();
9193 match self {
9294 Self::MainMenu(_) => pages_config.main_menu.clone(),
95 Self::Subscriptions(_) => pages_config.subscriptions.clone(),
9396 Self::Search(_) => pages_config.search.clone(),
9497 Self::SingleItem(_) => pages_config.singleitem.clone(),
9598 Self::ChannelDisplay(_) => pages_config.channeldisplay.clone(),
@@ -101,6 +104,7 @@ impl Page {
101104 let pages_config = framework.data.global.get::<PagesConfig>().unwrap();
102105 match self {
103106 Self::MainMenu(_) => pages_config.main_menu.message.clone(),
107 Self::Subscriptions(_) => pages_config.subscriptions.message.clone(),
104108 Self::Search(_) => pages_config.search.message.clone(),
105109 Self::SingleItem(_) => pages_config.singleitem.message.clone(),
106110 Self::ChannelDisplay(_) => pages_config.channeldisplay.message.clone(),
src/global/structs/subscriptions.rs +234 −28
@@ -1,46 +1,107 @@
1use super::*;
2use crate::global::{
3 functions::{download_all_images, DownloadRequest},
4 traits::{Collection, CollectionItem},
5};
6use home::home_dir;
17use serde::*;
2use std::{collections::HashMap, error::Error, sync::mpsc, thread};
3// use rayon::prelude::*;
4use super::{InvidiousClient, Item, MiniVideoItem};
5use crate::config::MainConfig;
8use std::{
9 error::Error,
10 fmt::Display,
11 fs::{self, OpenOptions},
12 io::Write,
13 sync::{atomic::AtomicU32, mpsc, Arc},
14 thread,
15};
16use typemap::Key;
617
7#[derive(Serialize, Deserialize)]
18#[derive(Serialize, Deserialize, Default, Clone)]
819/// id, videos
9pub struct Subscriptions(pub HashMap<String, Vec<MiniVideoItem>>);
20pub struct Subscriptions(pub Vec<SubItem>);
21
22impl Key for Subscriptions {
23 type Value = Self;
24}
1025
1126impl Subscriptions {
1227 /// Res<(success, failed)>
13 pub fn sync(&mut self, client: &InvidiousClient, mainconfig: &MainConfig) -> (u32, u32) {
14 let mut failed: u32 = 0;
15 let mut success: u32 = 0;
28 pub fn sync(
29 &mut self,
30 client: &InvidiousClient,
31 image_index: usize,
32 download_thumbnails: bool,
33 ) -> (u32, u32) {
34 let failed = Arc::new(AtomicU32::new(0));
35 let success = Arc::new(AtomicU32::new(0));
1636
1737 let (tx, rx) = mpsc::channel();
18 let image_index = mainconfig.image_index;
38 let mut channels = Vec::new();
39 std::mem::swap(&mut self.0, &mut channels);
1940
20 self.0.keys().for_each(|k| {
41 channels.into_iter().for_each(|mut item| {
2142 let tx = tx.clone();
2243 let client = client.clone();
23 let k = k.clone();
44 let success = success.clone();
45 let failed = failed.clone();
2446 thread::spawn(move || {
25 let res = sync_one(&k, &client, image_index).ok();
26 tx.send((k, res))
47 let res = sync_one(&item.channel.id, &client, image_index, download_thumbnails);
48 match res {
49 Ok(synced) => {
50 success.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
51 item = synced;
52 }
53 Err(_) => {
54 failed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
55 item.videos.clear()
56 }
57 }
58 tx.send(item)
2759 });
2860 });
2961
30 for res in rx {
31 match res {
32 (id, Some(videos)) => {
33 self.0.insert(id, videos);
34 success += 1;
35 }
36 (id, None) => {
37 self.0.get_mut(&id).unwrap().clear();
38 failed += 1;
39 }
62 for item in rx {
63 self.0.push(item);
64 }
65
66 self.0.sort();
67
68 let _ = self.save();
69
70 (
71 success.load(std::sync::atomic::Ordering::Relaxed),
72 failed.load(std::sync::atomic::Ordering::Relaxed),
73 )
74 }
75
76 pub fn sync_one(
77 &mut self,
78 id: &str,
79 client: &InvidiousClient,
80 image_index: usize,
81 download_thumbnails: bool,
82 ) -> Result<(), Box<dyn Error>> {
83 let synced = sync_one(id, client, image_index, download_thumbnails)?;
84 for item in self.0.iter_mut() {
85 if *item == synced {
86 *item = synced;
87 return Ok(());
4088 }
4189 }
4290
43 (success, failed)
91 self.0.push(synced);
92 self.0.sort();
93
94 self.save()?;
95 Ok(())
96 }
97
98 pub fn remove_one(&mut self, id: &str) -> bool {
99 if let Some(i) = self.0.iter().position(|item| item.channel.id == id) {
100 self.0.remove(i);
101 return true;
102 }
103
104 false
44105 }
45106}
46107
@@ -48,8 +109,24 @@ fn sync_one(
48109 id: &str,
49110 client: &InvidiousClient,
50111 image_index: usize,
51) -> Result<Vec<MiniVideoItem>, Box<dyn Error>> {
52 Ok(client
112 download_thumbnails: bool,
113) -> Result<SubItem, Box<dyn Error>> {
114 let (tx, rx) = mpsc::sync_channel(1);
115
116 let client2 = client.clone();
117 let id2 = id.to_string();
118 thread::spawn(move || {
119 tx.send(
120 client2
121 .0
122 .channel(&id2, None)
123 .map(|channel| Item::from_full_channel(channel, image_index).into_fullchannel())
124 .ok(),
125 )
126 .unwrap();
127 });
128
129 let videos = client
53130 .0
54131 .channel_videos(id, None)?
55132 .videos
@@ -59,5 +136,134 @@ fn sync_one(
59136 .into_minivideo()
60137 .unwrap()
61138 })
62 .collect())
139 .collect::<Vec<_>>();
140
141 let channel = rx
142 .recv()
143 .unwrap()
144 .ok_or(Errors::StrError("failed to get channel info {id}"))??;
145
146 if download_thumbnails {
147 let thumbnails: Vec<Option<DownloadRequest>> = videos
148 .iter()
149 .map(|video| {
150 Some(DownloadRequest {
151 url: video.thumbnail_url.clone(),
152 id: video.id.clone(),
153 })
154 })
155 .chain(
156 [Some(DownloadRequest {
157 url: channel.thumbnail_url.clone(),
158 id: channel.id.clone(),
159 })]
160 .into_iter(),
161 )
162 .collect::<Vec<_>>();
163 thread::spawn(move || {
164 download_all_images(thumbnails);
165 });
166 }
167
168 Ok(SubItem { channel, videos })
169}
170
171#[derive(Clone, Serialize, Deserialize)]
172pub struct SubItem {
173 pub channel: FullChannelItem,
174 pub videos: Vec<MiniVideoItem>,
175}
176
177impl Eq for SubItem {}
178impl Ord for SubItem {
179 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
180 self.partial_cmp(other).unwrap()
181 }
182}
183
184impl Display for SubItem {
185 fn fmt(&self, f: &mut __private::Formatter<'_>) -> std::fmt::Result {
186 f.write_str(&self.channel.name)
187 }
188}
189
190impl PartialEq for SubItem {
191 fn eq(&self, other: &Self) -> bool {
192 self.channel.id == other.channel.id
193 }
194}
195
196impl PartialOrd for SubItem {
197 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
198 self.channel.name.partial_cmp(&other.channel.name)
199 }
200}
201
202impl CollectionItem for SubItem {
203 fn id(&self) -> Option<&str> {
204 Some(&self.channel.id)
205 }
206
207 fn children_ids(&self) -> Vec<&str> {
208 self.videos
209 .iter()
210 .map(|video| video.id.as_str())
211 .collect::<_>()
212 }
213}
214
215impl Collection<SubItem> for Subscriptions {
216 const INDEX_PATH: &'static str = ".local/share/youtube-tui/subscriptions.json";
217
218 fn items(&self) -> &Vec<SubItem> {
219 &self.0
220 }
221
222 fn items_mut(&mut self) -> &mut Vec<SubItem> {
223 &mut self.0
224 }
225
226 fn from_items(items: Vec<SubItem>) -> Self {
227 Self(items)
228 }
229
230 fn save(&self) -> Result<(), Box<dyn Error>> {
231 let mut file = OpenOptions::new()
232 .truncate(true)
233 .write(true)
234 .create(true)
235 .open(home_dir().unwrap().join(Self::INDEX_PATH))?;
236
237 let save_string = serde_json::to_string_pretty(self)?;
238 file.write_all(save_string.as_bytes())?;
239 Ok(())
240 }
241
242 fn push(&mut self, _: SubItem, _: Option<usize>) -> Result<(), Box<dyn Error>> {
243 unimplemented!("not in use");
244 }
245
246 fn load() -> Self {
247 let path = home_dir().unwrap().join(Self::INDEX_PATH);
248 let res = (|| -> Result<Self, Box<dyn Error>> {
249 let file_string = fs::read_to_string(&path)?;
250 let deserialized = serde_json::from_str(&file_string)?;
251 Ok(deserialized)
252 })();
253
254 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
255 // which case returns Self::default()
256 if let Ok(subs) = res {
257 subs
258 } else {
259 // if the file does exist, back it up
260 // if it doesn't exist, it will throw an error but we dont care
261 let mut new_path = path.clone();
262 new_path.pop();
263 new_path.push(format!("index-{}.json", chrono::offset::Local::now(),));
264 let _ = fs::rename(&path, &new_path);
265
266 Self::default()
267 }
268 }
63269}
src/global/structs/tasks.rs −1
@@ -56,7 +56,6 @@ impl TaskQueue {
5656 RenderTask::Only(renders) => {
5757 if !renders.contains(&(x, y)) {
5858 renders.push((x, y));
59 println!("{:?}", self.render);
6059 }
6160 }
6261 RenderTask::None => self.render = RenderTask::Only(vec![(x, y)]),
src/global/structs/watchhistory.rs +5 −1
@@ -9,7 +9,7 @@ impl Key for WatchHistory {
99 type Value = Self;
1010}
1111
12impl Collection for WatchHistory {
12impl Collection<Item> for WatchHistory {
1313 const INDEX_PATH: &'static str = ".local/share/youtube-tui/watch_history.json";
1414
1515 fn items(&self) -> &Vec<Item> {
@@ -19,4 +19,8 @@ impl Collection for WatchHistory {
1919 fn items_mut(&mut self) -> &mut Vec<Item> {
2020 &mut self.0
2121 }
22
23 fn from_items(items: Vec<Item>) -> Self {
24 Self(items)
25 }
2226}
src/global/traits/collection.rs +24 −19
@@ -1,4 +1,3 @@
1use crate::global::structs::Item;
21use home::home_dir;
32use serde::{de::DeserializeOwned, Serialize};
43use std::{
@@ -6,16 +5,23 @@ use std::{
65 fs::{self, OpenOptions},
76 io::Write,
87};
9use typemap::Key;
108
11pub trait Collection
9pub trait CollectionItem {
10 fn id(&self) -> Option<&str>;
11 fn children_ids(&self) -> Vec<&str>;
12}
13
14pub trait Collection<T>
1215where
13 Self: Default + Clone + Serialize + DeserializeOwned + Key,
16 Self: Default + Clone + Serialize + DeserializeOwned,
17 T: Serialize + DeserializeOwned + CollectionItem,
1418{
1519 const INDEX_PATH: &'static str;
1620
17 fn items(&self) -> &Vec<Item>;
18 fn items_mut(&mut self) -> &mut Vec<Item>;
21 fn items(&self) -> &Vec<T>;
22 fn items_mut(&mut self) -> &mut Vec<T>;
23
24 fn from_items(items: Vec<T>) -> Self;
1925
2026 /// saves the current state of watch history into a file
2127 fn save(&self) -> Result<(), Box<dyn Error>> {
@@ -41,7 +47,7 @@ where
4147 }
4248
4349 /// add an item to watch history
44 fn push(&mut self, item: Item, max_length: Option<usize>) -> Result<(), Box<dyn Error>> {
50 fn push(&mut self, item: T, max_length: Option<usize>) -> Result<(), Box<dyn Error>> {
4551 let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
4652
4753 // removes duplicates and place them on top (if exists)
@@ -72,7 +78,7 @@ where
7278 }
7379
7480 /// loads watch history from file
75 fn load() -> Vec<Item> {
81 fn load() -> Self {
7682 let path = home_dir().unwrap().join(Self::INDEX_PATH);
7783 let res = (|| -> Result<Vec<String>, Box<dyn Error>> {
7884 let file_string = fs::read_to_string(&path)?;
@@ -82,7 +88,7 @@ where
8288
8389 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
8490 // which case returns Self::default()
85 if let Ok(deserialized) = res {
91 let items = if let Ok(deserialized) = res {
8692 let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
8793 deserialized
8894 .into_iter()
@@ -98,7 +104,9 @@ where
98104 let _ = fs::rename(&path, &new_path);
99105
100106 Vec::new()
101 }
107 };
108
109 Self::from_items(items)
102110 }
103111
104112 /// moves thumbnails of videos in watch history from cache back to storage when exiting, so that thumbnails can be viewed offline
@@ -121,15 +129,12 @@ where
121129 store_info_path.join(format!("{id}.json")),
122130 );
123131
124 if let Item::FullPlaylist(fullplaylist) = item {
125 fullplaylist.videos.iter().for_each(|video| {
126 let id = video.id().unwrap_or("invalid-dump");
127 let _ = fs::rename(
128 cache_thumbnails_path.join(id),
129 store_thumbnails_path.join(id),
130 );
131 })
132 }
132 item.children_ids().iter().for_each(|id| {
133 let _ = fs::rename(
134 cache_thumbnails_path.join(id),
135 store_thumbnails_path.join(id),
136 );
137 })
133138 })
134139 }
135140
src/init.rs +3 −2
@@ -42,11 +42,12 @@ pub fn init(
4242 framework
4343 .data
4444 .global
45 .insert::<WatchHistory>(WatchHistory(WatchHistory::load()));
45 .insert::<WatchHistory>(WatchHistory::load());
4646 framework
4747 .data
4848 .global
49 .insert::<Library>(Library(Library::load()));
49 .insert::<Subscriptions>(Subscriptions::load());
50 framework.data.global.insert::<Library>(Library::load());
5051 framework.data.global.insert::<Message>(Message::None);
5152 framework.data.global.insert::<Status>(Status {
5253 provider: framework.data.global.get::<MainConfig>().unwrap().provider,
src/items/channellist.rs added +167
@@ -0,0 +1,167 @@
1use crossterm::event::KeyCode;
2use tui::{layout::Constraint, style::Style};
3use tui_additions::{
4 framework::FrameworkItem,
5 widgets::{Grid, TextList},
6};
7
8use crate::{config::AppearanceConfig, global::structs::*};
9
10use super::ItemInfo;
11
12#[derive(Clone)]
13pub struct ChannelList {
14 pub selector: TextList,
15 pub channel_display: ItemInfo,
16 pub grid: Grid,
17}
18
19impl Default for ChannelList {
20 fn default() -> Self {
21 Self {
22 selector: TextList::default(),
23 channel_display: ItemInfo::default(),
24 grid: Grid::new(
25 vec![Constraint::Percentage(40), Constraint::Percentage(60)],
26 vec![Constraint::Percentage(100)],
27 )
28 .unwrap(),
29 }
30 }
31}
32
33impl ChannelList {
34 fn update_appearance(
35 &mut self,
36 info: &tui_additions::framework::ItemInfo,
37 appearance: &AppearanceConfig,
38 ) {
39 if info.selected {
40 self.grid
41 .set_border_style(Style::default().fg(appearance.colors.outline_selected));
42 self.selector
43 .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
44 } else if info.hover {
45 self.grid
46 .set_border_style(Style::default().fg(appearance.colors.outline_hover));
47 self.selector
48 .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
49 } else {
50 self.grid
51 .set_border_style(Style::default().fg(appearance.colors.outline));
52 self.selector
53 .set_cursor_style(Style::default().fg(appearance.colors.outline));
54 }
55 }
56}
57
58impl FrameworkItem for ChannelList {
59 fn load_item(
60 &mut self,
61 framework: &mut tui_additions::framework::FrameworkClean,
62 _info: tui_additions::framework::ItemInfo,
63 ) -> Result<(), Box<dyn std::error::Error>> {
64 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
65 self.selector.set_border_type(appearance.borders);
66 self.grid.set_border_type(appearance.borders);
67
68 self.selector.set_items(
69 &["Sync all subscriptions".to_string()]
70 .into_iter()
71 .chain(
72 framework
73 .data
74 .global
75 .get::<Subscriptions>()
76 .unwrap()
77 .0
78 .iter()
79 .map(|subtiem| subtiem.to_string()),
80 )
81 .collect::<Vec<_>>(),
82 )?;
83
84 if self.selector.selected >= self.selector.items.len() {
85 self.selector.last()?;
86 }
87
88 Ok(())
89 }
90
91 fn render(
92 &mut self,
93 frame: &mut tui::Frame<tui::backend::CrosstermBackend<std::io::Stdout>>,
94 framework: &mut tui_additions::framework::FrameworkClean,
95 area: tui::layout::Rect,
96 popup_render: bool,
97 info: tui_additions::framework::ItemInfo,
98 ) {
99 if popup_render {
100 return;
101 }
102
103 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
104
105 self.update_appearance(&info, appearance);
106 let chunks = self.grid.chunks(area).unwrap()[0].clone();
107 frame.render_widget(self.grid.clone(), area);
108 self.selector.set_height(chunks[1].height);
109 frame.render_widget(self.selector.clone(), chunks[1]);
110 self.channel_display
111 .render(frame, framework, chunks[0], popup_render, info);
112 }
113
114 fn key_event(
115 &mut self,
116 framework: &mut tui_additions::framework::FrameworkClean,
117 key: crossterm::event::KeyEvent,
118 _info: tui_additions::framework::ItemInfo,
119 ) -> Result<(), Box<dyn std::error::Error>> {
120 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
121 let previously_selected = self.selector.selected;
122 match key.code {
123 KeyCode::Down if self.selector.down().is_ok() => tasks.priority.push(Task::RenderAll),
124 KeyCode::Up if self.selector.up().is_ok() => tasks.priority.push(Task::RenderAll),
125 KeyCode::Left if self.selector.first().is_ok() => tasks.priority.push(Task::RenderAll),
126 KeyCode::Right if self.selector.last().is_ok() => tasks.priority.push(Task::RenderAll),
127 _ => return Ok(()),
128 }
129
130 if self.selector.selected == 0 {
131 if previously_selected != 0 {
132 self.channel_display.item = None;
133 tasks.priority.push(Task::ClearPage);
134 framework
135 .data
136 .global
137 .get_mut::<Status>()
138 .unwrap()
139 .render_image = true;
140 }
141 return Ok(());
142 }
143
144 match framework
145 .data
146 .global
147 .get::<Subscriptions>()
148 .unwrap()
149 .0
150 .get(self.selector.selected - 1)
151 {
152 Some(item)
153 if item.channel.id
154 != match &self.channel_display.item {
155 Some(displayed) => displayed.id().unwrap_or_default(),
156 None => "",
157 } =>
158 {
159 self.channel_display.item = Some(Item::FullChannel(item.channel.clone()))
160 }
161 Some(_) => {}
162 None => self.channel_display.item = None,
163 };
164
165 Ok(())
166 }
167}
src/items/itemlist.rs −1
@@ -309,7 +309,6 @@ impl FrameworkItem for ItemList {
309309 .map(|item| Item::from_popular_item(item, image_index))
310310 .collect();
311311 }
312 Page::MainMenu(MainMenuPage::Subscriptions) => {}
313312 Page::MainMenu(MainMenuPage::Library) => {
314313 let history = framework.data.global.get::<Library>().unwrap();
315314 self.items = history.0.clone().into_iter().rev().collect();
src/items/mod.rs +2
@@ -15,3 +15,5 @@ mod singleitem;
1515pub use singleitem::*;
1616mod channeldisplay;
1717pub use channeldisplay::*;
18mod channellist;
19pub use channellist::*;
src/items/pagebutton.rs +25 −37
@@ -37,26 +37,20 @@ impl PageButton {
3737 r#type: ChannelDisplayPageType::Playlists,
3838 }),
3939 Self::History => Page::MainMenu(MainMenuPage::History),
40 Self::Subscriptions => Page::MainMenu(MainMenuPage::Subscriptions),
40 Self::Subscriptions => Page::Subscriptions(None),
4141 Self::Library => Page::MainMenu(MainMenuPage::Library),
4242 }
4343 }
4444
45 fn update_toggleable(&mut self, page: &Page) {
46 if *self == Self::Popular || *self == Self::Trending {
47 match page {
48 Page::MainMenu(MainMenuPage::Popular) => *self = Self::Popular,
49 Page::MainMenu(MainMenuPage::Trending) => *self = Self::Trending,
50 _ => {}
51 }
52 } else if *self == Self::Subscriptions || *self == Self::Library {
53 // match page {
54 // Page::MainMenu(MainMenuPage::Subscriptions) => *self = Self::Subscriptions,
55 // Page::MainMenu(MainMenuPage::Library) => *self = Self::Library,
56 // _ => {}
57 // }
58 }
59 }
45 // fn update_toggleable(&mut self, page: &Page) {
46 // if *self == Self::Popular || *self == Self::Trending {
47 // match page {
48 // Page::MainMenu(MainMenuPage::Popular) => *self = Self::Popular,
49 // Page::MainMenu(MainMenuPage::Trending) => *self = Self::Trending,
50 // _ => {}
51 // }
52 // }
53 // }
6054}
6155
6256impl ToString for PageButton {
@@ -75,14 +69,15 @@ impl ToString for PageButton {
7569}
7670
7771impl FrameworkItem for PageButton {
78 fn load_item(
79 &mut self,
80 framework: &mut tui_additions::framework::FrameworkClean,
81 _info: tui_additions::framework::ItemInfo,
82 ) -> Result<(), Box<dyn std::error::Error>> {
83 self.update_toggleable(framework.data.state.get::<Page>().unwrap());
84 Ok(())
85 }
72 // fn load_item(
73 // &mut self,
74 // framework: &mut tui_additions::framework::FrameworkClean,
75 // _info: tui_additions::framework::ItemInfo,
76 // ) -> Result<(), Box<dyn std::error::Error>> {
77 // self.update_toggleable(framework.data.state.get::<Page>().unwrap());
78 // Ok(())
79 // }
80
8681 // it is basically a paragraph (text) with borders
8782 fn render(
8883 &mut self,
@@ -122,19 +117,12 @@ impl FrameworkItem for PageButton {
122117 let current_page = framework.data.state.get::<Page>().unwrap();
123118 let self_page = self.page(current_page);
124119
125 if self_page == *current_page {
126 match self {
127 Self::Trending => *self = Self::Popular,
128 Self::Popular => *self = Self::Trending,
129 // Self::Subscriptions => *self = Self::Library,
130 // Self::Library => *self = Self::Subscriptions,
131 _ => {
132 *framework.data.global.get_mut::<Message>().unwrap() =
133 Message::Message(String::from("You are already on this page"));
134 return false;
135 }
136 }
137 }
120 // if self_page == *current_page {
121 // match self {
122 // Self::Trending => *self = Self::Popular,
123 // Self::Popular => *self = Self::Trending,
124 // }
125 // }
138126
139127 framework
140128 .data