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 {
40 Page::MainMenu(MainMenuPage::Trending) => get_command(key, &self.trending), 40 Page::MainMenu(MainMenuPage::Trending) => get_command(key, &self.trending),
41 Page::MainMenu(MainMenuPage::Popular) => get_command(key, &self.popular), 41 Page::MainMenu(MainMenuPage::Popular) => get_command(key, &self.popular),
42 Page::MainMenu(MainMenuPage::History) => get_command(key, &self.watchhistory), 42 Page::MainMenu(MainMenuPage::History) => get_command(key, &self.watchhistory),
43 Page::MainMenu(MainMenuPage::Subscriptions) => get_command(key, &self.subscriptions),
44 Page::MainMenu(MainMenuPage::Library) => get_command(key, &self.libray), 43 Page::MainMenu(MainMenuPage::Library) => get_command(key, &self.libray),
44 Page::Subscriptions(_) => get_command(key, &self.subscriptions),
45 Page::SingleItem(SingleItemPage::Video(_)) => get_command(key, &self.video), 45 Page::SingleItem(SingleItemPage::Video(_)) => get_command(key, &self.video),
46 Page::SingleItem(SingleItemPage::Playlist(_)) => get_command(key, &self.playlist), 46 Page::SingleItem(SingleItemPage::Playlist(_)) => get_command(key, &self.playlist),
47 Page::ChannelDisplay(ChannelDisplayPage { 47 Page::ChannelDisplay(ChannelDisplayPage {
src/config/pages.rs +36 −3
@@ -28,6 +28,8 @@ impl Key for MinDimentions {
28pub struct PagesConfig { 28pub struct PagesConfig {
29 #[serde(default = "main_menu_default")] 29 #[serde(default = "main_menu_default")]
30 pub main_menu: PageConfig, 30 pub main_menu: PageConfig,
31 #[serde(default = "subscriptions_default")]
32 pub subscriptions: PageConfig,
31 #[serde(default = "search_default")] 33 #[serde(default = "search_default")]
32 pub search: PageConfig, 34 pub search: PageConfig,
33 #[serde(default = "singleitem_default")] 35 #[serde(default = "singleitem_default")]
@@ -48,6 +50,7 @@ impl Default for PagesConfig {
48 fn default() -> Self { 50 fn default() -> Self {
49 Self { 51 Self {
50 main_menu: main_menu_default(), 52 main_menu: main_menu_default(),
53 subscriptions: subscriptions_default(),
51 search: search_default(), 54 search: search_default(),
52 singleitem: singleitem_default(), 55 singleitem: singleitem_default(),
53 channeldisplay: channeldisplay_default(), 56 channeldisplay: channeldisplay_default(),
@@ -168,6 +171,8 @@ pub enum PageItems {
168 Subscriptions, 171 Subscriptions,
169 /// the library button which loads the saved page 172 /// the library button which loads the saved page
170 Library, 173 Library,
174 /// Subscriptions list (channels)
175 ChannelList,
171 /// the search filters `...` button, displays a popup when selected 176 /// the search filters `...` button, displays a popup when selected
172 SearchFilters, 177 SearchFilters,
173 /// playlist and video info display 178 /// playlist and video info display
@@ -192,6 +197,7 @@ impl PageItems {
192 Self::History => Box::new(PageButton::History), 197 Self::History => Box::new(PageButton::History),
193 Self::Subscriptions => Box::new(PageButton::Subscriptions), 198 Self::Subscriptions => Box::new(PageButton::Subscriptions),
194 Self::Library => Box::new(PageButton::Library), 199 Self::Library => Box::new(PageButton::Library),
200 Self::ChannelList => Box::<ChannelList>::default(),
195 Self::MessageBar => Box::<MessageBar>::default(), 201 Self::MessageBar => Box::<MessageBar>::default(),
196 Self::ItemList => Box::<ItemList>::default(), 202 Self::ItemList => Box::<ItemList>::default(),
197 Self::SearchFilters => Box::<SearchFilter>::default(), 203 Self::SearchFilters => Box::<SearchFilter>::default(),
@@ -215,7 +221,9 @@ impl PageItems {
215 | Self::ChannelPlaylists => Constraint::Length(15), 221 | Self::ChannelPlaylists => Constraint::Length(15),
216 Self::SearchBar => Constraint::Min(16), 222 Self::SearchBar => Constraint::Min(16),
217 Self::MessageBar => Constraint::Min(3), 223 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 }
219 Self::SearchFilters => Constraint::Length(5), 227 Self::SearchFilters => Constraint::Length(5),
220 } 228 }
221 } 229 }
@@ -233,7 +241,9 @@ impl PageItems {
233 | Self::MessageBar 241 | Self::MessageBar
234 | Self::SearchBar 242 | Self::SearchBar
235 | Self::SearchFilters => Constraint::Length(3), 243 | 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 }
237 } 247 }
238 } 248 }
239} 249}
@@ -267,7 +277,11 @@ fn main_menu_default() -> PageConfig {
267 layout: vec![ 277 layout: vec![
268 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false), 278 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
269 PageRow::from_vec( 279 PageRow::from_vec(
270 vec![PageItems::Popular, PageItems::Library, PageItems::History], 280 vec![
281 PageItems::Library,
282 PageItems::Subscriptions,
283 PageItems::History,
284 ],
271 true, 285 true,
272 ), 286 ),
273 PageRow::from_vec(vec![PageItems::ItemList], false), 287 PageRow::from_vec(vec![PageItems::ItemList], false),
@@ -317,3 +331,22 @@ fn channeldisplay_default() -> PageConfig {
317 message: String::from("Loading channel details..."), 331 message: String::from("Loading channel details..."),
318 } 332 }
319} 333}
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;
2use std::{error::Error, fs}; 2use std::{error::Error, fs};
3use tui_additions::framework::Framework; 3use tui_additions::framework::Framework;
4 4
5use crate::global::{structs::WatchHistory, traits::Collection}; 5use crate::global::{structs::*, traits::Collection};
6 6
7/// function to run when the app ends 7/// function to run when the app ends
8// exit tasks: 8// exit tasks:
9// - move thumbnails of videos in watch history to `~/.local/share/youtube-tui/watch_history/thumbnails` 9// - move thumbnails of videos in watch history to `~/.local/share/youtube-tui/watch_history/thumbnails`
10// - remove `~/.cache` 10// - remove `~/.cache`
11pub fn exit(framework: &Framework) -> Result<(), Box<dyn Error>> { 11pub fn exit(framework: &Framework) -> Result<(), Box<dyn Error>> {
12 if let Some(history) = framework.data.global.get::<WatchHistory>() { 12 framework
13 history.exit_move() 13 .data
14 } 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();
15 25
16 let home_dir = home_dir().unwrap(); 26 let home_dir = home_dir().unwrap();
17 let cache_path = home_dir.join(".cache/youtube-tui/"); 27 let cache_path = home_dir.join(".cache/youtube-tui/");
src/global/functions/mod.rs +6 −6
@@ -1,18 +1,18 @@
1//! public functions 1//! public functions
2mod secs_display_string; 2mod secs_display_string;
3pub use secs_display_string::secs_display_string; 3pub use secs_display_string::*;
4mod viewcount_text; 4mod viewcount_text;
5pub use viewcount_text::viewcount_text; 5pub use viewcount_text::*;
6mod date_text; 6mod date_text;
7pub use date_text::date_text; 7pub use date_text::*;
8mod download_all_images; 8mod download_all_images;
9pub use download_all_images::download_all_images; 9pub use download_all_images::*;
10mod popup_area; 10mod popup_area;
11pub use popup_area::popup_area; 11pub use popup_area::*;
12mod run_command; 12mod run_command;
13pub use run_command::*; 13pub use run_command::*;
14mod command_capture; 14mod command_capture;
15pub use command_capture::command_capture; 15pub use command_capture::*;
16mod fake_rand; 16mod fake_rand;
17pub use fake_rand::*; 17pub use fake_rand::*;
18#[cfg(feature = "clipboard")] 18#[cfg(feature = "clipboard")]
src/global/functions/run_command.rs +81 −2
@@ -124,7 +124,7 @@ pub fn run_single_command(
124 "popular" => Some(Page::MainMenu(MainMenuPage::Popular)), 124 "popular" => Some(Page::MainMenu(MainMenuPage::Popular)),
125 "trending" => Some(Page::MainMenu(MainMenuPage::Trending)), 125 "trending" => Some(Page::MainMenu(MainMenuPage::Trending)),
126 "watchhistory" => Some(Page::MainMenu(MainMenuPage::History)), 126 "watchhistory" => Some(Page::MainMenu(MainMenuPage::History)),
127 "subscriptions" => Some(Page::MainMenu(MainMenuPage::Subscriptions)), 127 "subscriptions" | "subs" => Some(Page::Subscriptions(None)),
128 "library" => Some(Page::MainMenu(MainMenuPage::Library)), 128 "library" => Some(Page::MainMenu(MainMenuPage::Library)),
129 "channel" => { 129 "channel" => {
130 if command.len() == 2 { 130 if command.len() == 2 {
@@ -212,7 +212,7 @@ pub fn run_single_command(
212 ["popular"] => run_single_command(&["loadpage", "popular"], framework, terminal), 212 ["popular"] => run_single_command(&["loadpage", "popular"], framework, terminal),
213 ["trending"] => run_single_command(&["loadpage", "trending"], framework, terminal), 213 ["trending"] => run_single_command(&["loadpage", "trending"], framework, terminal),
214 ["watchhistory"] => run_single_command(&["loadpage", "watchhistory"], framework, terminal), 214 ["watchhistory"] => run_single_command(&["loadpage", "watchhistory"], framework, terminal),
215 ["subscriptions"] => { 215 ["subscriptions"] | ["subs"] => {
216 run_single_command(&["loadpage", "subscriptions"], framework, terminal) 216 run_single_command(&["loadpage", "subscriptions"], framework, terminal)
217 } 217 }
218 ["bookmarks"] => run_single_command(&["loadpage", "bookmarks"], framework, terminal), 218 ["bookmarks"] => run_single_command(&["loadpage", "bookmarks"], framework, terminal),
@@ -345,6 +345,83 @@ pub fn run_single_command(
345 *framework.data.global.get_mut::<Message>().unwrap() = 345 *framework.data.global.get_mut::<Message>().unwrap() =
346 Message::Success(String::from("Copied to clipboad")); 346 Message::Success(String::from("Copied to clipboad"));
347 } 347 }
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 }
348 _ => { 425 _ => {
349 *framework.data.global.get_mut::<Message>().unwrap() = 426 *framework.data.global.get_mut::<Message>().unwrap() =
350 Message::Error(format!("Unknown command: `{}`", command.join(" "))); 427 Message::Error(format!("Unknown command: `{}`", command.join(" ")));
@@ -424,6 +501,8 @@ const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
424 \x1b[33mbookmark [id]\x1b[0m Bookmark item with ID (item must be already loaded) 501 \x1b[33mbookmark [id]\x1b[0m Bookmark item with ID (item must be already loaded)
425 \x1b[33munmark [id]\x1b[0m Remove bookmark item with ID 502 \x1b[33munmark [id]\x1b[0m Remove bookmark item with ID
426 \x1b[33mtogglemark [id]\x1b[0m Toggle bookmark status 503 \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
427 506
428\x1b[91mALT:\x1b[0m 507\x1b[91mALT:\x1b[0m
429\x1b[37malts links back to the original command\x1b[30m 508\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) {
66 } 66 }
67 }, 67 },
68 )], 68 )],
69 Page::MainMenu(MainMenuPage::Subscriptions) => vec![( 69 Page::Subscriptions(_) => vec![(
70 String::from("url"), 70 String::from("url"),
71 match status.provider { 71 match status.provider {
72 Provider::YouTube => String::from("https://www.youtube.com/feed/subscriptions"), 72 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};
2use invidious::{channel::Channel, hidden::*, universal::Playlist as FullPlaylist, video::Video}; 2use invidious::{channel::Channel, hidden::*, universal::Playlist as FullPlaylist, video::Video};
3use serde::{Deserialize, Serialize}; 3use serde::{Deserialize, Serialize};
4use std::fmt::Display; 4use std::fmt::Display;
@@ -21,6 +21,24 @@ pub enum Item {
21 Unknown(SearchItemTransition), 21 Unknown(SearchItemTransition),
22} 22}
23 23
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
24/// stores information of a previewed video 42/// stores information of a previewed video
25#[derive(Clone, Serialize, Deserialize)] 43#[derive(Clone, Serialize, Deserialize)]
26pub struct MiniVideoItem { 44pub struct MiniVideoItem {
src/global/structs/library.rs +5 −1
@@ -11,7 +11,7 @@ impl Key for Library {
11 type Value = Self; 11 type Value = Self;
12} 12}
13 13
14impl Collection for Library { 14impl Collection<Item> for Library {
15 const INDEX_PATH: &'static str = ".local/share/youtube-tui/library.json"; 15 const INDEX_PATH: &'static str = ".local/share/youtube-tui/library.json";
16 16
17 fn items(&self) -> &Vec<Item> { 17 fn items(&self) -> &Vec<Item> {
@@ -21,4 +21,8 @@ impl Collection for Library {
21 fn items_mut(&mut self) -> &mut Vec<Item> { 21 fn items_mut(&mut self) -> &mut Vec<Item> {
22 &mut self.0 22 &mut self.0
23 } 23 }
24
25 fn from_items(items: Vec<Item>) -> Self {
26 Self(items)
27 }
24} 28}
src/global/structs/page.rs +5 −1
@@ -9,6 +9,8 @@ use typemap::Key;
9#[derive(Clone, PartialEq, Eq)] 9#[derive(Clone, PartialEq, Eq)]
10pub enum Page { 10pub enum Page {
11 MainMenu(MainMenuPage), 11 MainMenu(MainMenuPage),
12 // Option<new channel selected index>
13 Subscriptions(Option<usize>),
12 Search(Search), 14 Search(Search),
13 SingleItem(SingleItemPage), 15 SingleItem(SingleItemPage),
14 ChannelDisplay(ChannelDisplayPage), 16 ChannelDisplay(ChannelDisplayPage),
@@ -20,6 +22,7 @@ impl Debug for Page {
20 "{}(_)", 22 "{}(_)",
21 match self { 23 match self {
22 Self::MainMenu(_) => "MainMenu", 24 Self::MainMenu(_) => "MainMenu",
25 Self::Subscriptions(_) => "Subscriptions",
23 Self::Search(_) => "Search", 26 Self::Search(_) => "Search",
24 Self::SingleItem(_) => "SingleItem", 27 Self::SingleItem(_) => "SingleItem",
25 Self::ChannelDisplay(_) => "ChannelDisplay", 28 Self::ChannelDisplay(_) => "ChannelDisplay",
@@ -54,7 +57,6 @@ pub enum MainMenuPage {
54 Trending, 57 Trending,
55 Popular, 58 Popular,
56 History, 59 History,
57 Subscriptions,
58 Library, 60 Library,
59} 61}
60 62
@@ -90,6 +92,7 @@ impl Page {
90 let pages_config = framework.data.global.get::<PagesConfig>().unwrap(); 92 let pages_config = framework.data.global.get::<PagesConfig>().unwrap();
91 match self { 93 match self {
92 Self::MainMenu(_) => pages_config.main_menu.clone(), 94 Self::MainMenu(_) => pages_config.main_menu.clone(),
95 Self::Subscriptions(_) => pages_config.subscriptions.clone(),
93 Self::Search(_) => pages_config.search.clone(), 96 Self::Search(_) => pages_config.search.clone(),
94 Self::SingleItem(_) => pages_config.singleitem.clone(), 97 Self::SingleItem(_) => pages_config.singleitem.clone(),
95 Self::ChannelDisplay(_) => pages_config.channeldisplay.clone(), 98 Self::ChannelDisplay(_) => pages_config.channeldisplay.clone(),
@@ -101,6 +104,7 @@ impl Page {
101 let pages_config = framework.data.global.get::<PagesConfig>().unwrap(); 104 let pages_config = framework.data.global.get::<PagesConfig>().unwrap();
102 match self { 105 match self {
103 Self::MainMenu(_) => pages_config.main_menu.message.clone(), 106 Self::MainMenu(_) => pages_config.main_menu.message.clone(),
107 Self::Subscriptions(_) => pages_config.subscriptions.message.clone(),
104 Self::Search(_) => pages_config.search.message.clone(), 108 Self::Search(_) => pages_config.search.message.clone(),
105 Self::SingleItem(_) => pages_config.singleitem.message.clone(), 109 Self::SingleItem(_) => pages_config.singleitem.message.clone(),
106 Self::ChannelDisplay(_) => pages_config.channeldisplay.message.clone(), 110 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;
1use serde::*; 7use serde::*;
2use std::{collections::HashMap, error::Error, sync::mpsc, thread}; 8use std::{
3// use rayon::prelude::*; 9 error::Error,
4use super::{InvidiousClient, Item, MiniVideoItem}; 10 fmt::Display,
5use crate::config::MainConfig; 11 fs::{self, OpenOptions},
12 io::Write,
13 sync::{atomic::AtomicU32, mpsc, Arc},
14 thread,
15};
16use typemap::Key;
6 17
7#[derive(Serialize, Deserialize)] 18#[derive(Serialize, Deserialize, Default, Clone)]
8/// id, videos 19/// 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}
10 25
11impl Subscriptions { 26impl Subscriptions {
12 /// Res<(success, failed)> 27 /// Res<(success, failed)>
13 pub fn sync(&mut self, client: &InvidiousClient, mainconfig: &MainConfig) -> (u32, u32) { 28 pub fn sync(
14 let mut failed: u32 = 0; 29 &mut self,
15 let mut success: u32 = 0; 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));
16 36
17 let (tx, rx) = mpsc::channel(); 37 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);
19 40
20 self.0.keys().for_each(|k| { 41 channels.into_iter().for_each(|mut item| {
21 let tx = tx.clone(); 42 let tx = tx.clone();
22 let client = client.clone(); 43 let client = client.clone();
23 let k = k.clone(); 44 let success = success.clone();
45 let failed = failed.clone();
24 thread::spawn(move || { 46 thread::spawn(move || {
25 let res = sync_one(&k, &client, image_index).ok(); 47 let res = sync_one(&item.channel.id, &client, image_index, download_thumbnails);
26 tx.send((k, res)) 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)
27 }); 59 });
28 }); 60 });
29 61
30 for res in rx { 62 for item in rx {
31 match res { 63 self.0.push(item);
32 (id, Some(videos)) => { 64 }
33 self.0.insert(id, videos); 65
34 success += 1; 66 self.0.sort();
35 } 67
36 (id, None) => { 68 let _ = self.save();
37 self.0.get_mut(&id).unwrap().clear(); 69
38 failed += 1; 70 (
39 } 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(());
40 } 88 }
41 } 89 }
42 90
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
44 } 105 }
45} 106}
46 107
@@ -48,8 +109,24 @@ fn sync_one(
48 id: &str, 109 id: &str,
49 client: &InvidiousClient, 110 client: &InvidiousClient,
50 image_index: usize, 111 image_index: usize,
51) -> Result<Vec<MiniVideoItem>, Box<dyn Error>> { 112 download_thumbnails: bool,
52 Ok(client 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
53 .0 130 .0
54 .channel_videos(id, None)? 131 .channel_videos(id, None)?
55 .videos 132 .videos
@@ -59,5 +136,134 @@ fn sync_one(
59 .into_minivideo() 136 .into_minivideo()
60 .unwrap() 137 .unwrap()
61 }) 138 })
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 }
63} 269}
src/global/structs/tasks.rs −1
@@ -56,7 +56,6 @@ impl TaskQueue {
56 RenderTask::Only(renders) => { 56 RenderTask::Only(renders) => {
57 if !renders.contains(&(x, y)) { 57 if !renders.contains(&(x, y)) {
58 renders.push((x, y)); 58 renders.push((x, y));
59 println!("{:?}", self.render);
60 } 59 }
61 } 60 }
62 RenderTask::None => self.render = RenderTask::Only(vec![(x, y)]), 61 RenderTask::None => self.render = RenderTask::Only(vec![(x, y)]),
src/global/structs/watchhistory.rs +5 −1
@@ -9,7 +9,7 @@ impl Key for WatchHistory {
9 type Value = Self; 9 type Value = Self;
10} 10}
11 11
12impl Collection for WatchHistory { 12impl Collection<Item> for WatchHistory {
13 const INDEX_PATH: &'static str = ".local/share/youtube-tui/watch_history.json"; 13 const INDEX_PATH: &'static str = ".local/share/youtube-tui/watch_history.json";
14 14
15 fn items(&self) -> &Vec<Item> { 15 fn items(&self) -> &Vec<Item> {
@@ -19,4 +19,8 @@ impl Collection for WatchHistory {
19 fn items_mut(&mut self) -> &mut Vec<Item> { 19 fn items_mut(&mut self) -> &mut Vec<Item> {
20 &mut self.0 20 &mut self.0
21 } 21 }
22
23 fn from_items(items: Vec<Item>) -> Self {
24 Self(items)
25 }
22} 26}
src/global/traits/collection.rs +24 −19
@@ -1,4 +1,3 @@
1use crate::global::structs::Item;
2use home::home_dir; 1use home::home_dir;
3use serde::{de::DeserializeOwned, Serialize}; 2use serde::{de::DeserializeOwned, Serialize};
4use std::{ 3use std::{
@@ -6,16 +5,23 @@ use std::{
6 fs::{self, OpenOptions}, 5 fs::{self, OpenOptions},
7 io::Write, 6 io::Write,
8}; 7};
9use typemap::Key;
10 8
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>
12where 15where
13 Self: Default + Clone + Serialize + DeserializeOwned + Key, 16 Self: Default + Clone + Serialize + DeserializeOwned,
17 T: Serialize + DeserializeOwned + CollectionItem,
14{ 18{
15 const INDEX_PATH: &'static str; 19 const INDEX_PATH: &'static str;
16 20
17 fn items(&self) -> &Vec<Item>; 21 fn items(&self) -> &Vec<T>;
18 fn items_mut(&mut self) -> &mut Vec<Item>; 22 fn items_mut(&mut self) -> &mut Vec<T>;
23
24 fn from_items(items: Vec<T>) -> Self;
19 25
20 /// saves the current state of watch history into a file 26 /// saves the current state of watch history into a file
21 fn save(&self) -> Result<(), Box<dyn Error>> { 27 fn save(&self) -> Result<(), Box<dyn Error>> {
@@ -41,7 +47,7 @@ where
41 } 47 }
42 48
43 /// add an item to watch history 49 /// 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>> {
45 let info = home_dir().unwrap().join(".cache/youtube-tui/info/"); 51 let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
46 52
47 // removes duplicates and place them on top (if exists) 53 // removes duplicates and place them on top (if exists)
@@ -72,7 +78,7 @@ where
72 } 78 }
73 79
74 /// loads watch history from file 80 /// loads watch history from file
75 fn load() -> Vec<Item> { 81 fn load() -> Self {
76 let path = home_dir().unwrap().join(Self::INDEX_PATH); 82 let path = home_dir().unwrap().join(Self::INDEX_PATH);
77 let res = (|| -> Result<Vec<String>, Box<dyn Error>> { 83 let res = (|| -> Result<Vec<String>, Box<dyn Error>> {
78 let file_string = fs::read_to_string(&path)?; 84 let file_string = fs::read_to_string(&path)?;
@@ -82,7 +88,7 @@ where
82 88
83 // if res is err, then the file either doesn't exist of has be altered incorrectly, in 89 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
84 // which case returns Self::default() 90 // which case returns Self::default()
85 if let Ok(deserialized) = res { 91 let items = if let Ok(deserialized) = res {
86 let info = home_dir().unwrap().join(".cache/youtube-tui/info/"); 92 let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
87 deserialized 93 deserialized
88 .into_iter() 94 .into_iter()
@@ -98,7 +104,9 @@ where
98 let _ = fs::rename(&path, &new_path); 104 let _ = fs::rename(&path, &new_path);
99 105
100 Vec::new() 106 Vec::new()
101 } 107 };
108
109 Self::from_items(items)
102 } 110 }
103 111
104 /// moves thumbnails of videos in watch history from cache back to storage when exiting, so that thumbnails can be viewed offline 112 /// 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
121 store_info_path.join(format!("{id}.json")), 129 store_info_path.join(format!("{id}.json")),
122 ); 130 );
123 131
124 if let Item::FullPlaylist(fullplaylist) = item { 132 item.children_ids().iter().for_each(|id| {
125 fullplaylist.videos.iter().for_each(|video| { 133 let _ = fs::rename(
126 let id = video.id().unwrap_or("invalid-dump"); 134 cache_thumbnails_path.join(id),
127 let _ = fs::rename( 135 store_thumbnails_path.join(id),
128 cache_thumbnails_path.join(id), 136 );
129 store_thumbnails_path.join(id), 137 })
130 );
131 })
132 }
133 }) 138 })
134 } 139 }
135 140
src/init.rs +3 −2
@@ -42,11 +42,12 @@ pub fn init(
42 framework 42 framework
43 .data 43 .data
44 .global 44 .global
45 .insert::<WatchHistory>(WatchHistory(WatchHistory::load())); 45 .insert::<WatchHistory>(WatchHistory::load());
46 framework 46 framework
47 .data 47 .data
48 .global 48 .global
49 .insert::<Library>(Library(Library::load())); 49 .insert::<Subscriptions>(Subscriptions::load());
50 framework.data.global.insert::<Library>(Library::load());
50 framework.data.global.insert::<Message>(Message::None); 51 framework.data.global.insert::<Message>(Message::None);
51 framework.data.global.insert::<Status>(Status { 52 framework.data.global.insert::<Status>(Status {
52 provider: framework.data.global.get::<MainConfig>().unwrap().provider, 53 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 {
309 .map(|item| Item::from_popular_item(item, image_index)) 309 .map(|item| Item::from_popular_item(item, image_index))
310 .collect(); 310 .collect();
311 } 311 }
312 Page::MainMenu(MainMenuPage::Subscriptions) => {}
313 Page::MainMenu(MainMenuPage::Library) => { 312 Page::MainMenu(MainMenuPage::Library) => {
314 let history = framework.data.global.get::<Library>().unwrap(); 313 let history = framework.data.global.get::<Library>().unwrap();
315 self.items = history.0.clone().into_iter().rev().collect(); 314 self.items = history.0.clone().into_iter().rev().collect();
src/items/mod.rs +2
@@ -15,3 +15,5 @@ mod singleitem;
15pub use singleitem::*; 15pub use singleitem::*;
16mod channeldisplay; 16mod channeldisplay;
17pub use channeldisplay::*; 17pub use channeldisplay::*;
18mod channellist;
19pub use channellist::*;
src/items/pagebutton.rs +25 −37
@@ -37,26 +37,20 @@ impl PageButton {
37 r#type: ChannelDisplayPageType::Playlists, 37 r#type: ChannelDisplayPageType::Playlists,
38 }), 38 }),
39 Self::History => Page::MainMenu(MainMenuPage::History), 39 Self::History => Page::MainMenu(MainMenuPage::History),
40 Self::Subscriptions => Page::MainMenu(MainMenuPage::Subscriptions), 40 Self::Subscriptions => Page::Subscriptions(None),
41 Self::Library => Page::MainMenu(MainMenuPage::Library), 41 Self::Library => Page::MainMenu(MainMenuPage::Library),
42 } 42 }
43 } 43 }
44 44
45 fn update_toggleable(&mut self, page: &Page) { 45 // fn update_toggleable(&mut self, page: &Page) {
46 if *self == Self::Popular || *self == Self::Trending { 46 // if *self == Self::Popular || *self == Self::Trending {
47 match page { 47 // match page {
48 Page::MainMenu(MainMenuPage::Popular) => *self = Self::Popular, 48 // Page::MainMenu(MainMenuPage::Popular) => *self = Self::Popular,
49 Page::MainMenu(MainMenuPage::Trending) => *self = Self::Trending, 49 // Page::MainMenu(MainMenuPage::Trending) => *self = Self::Trending,
50 _ => {} 50 // _ => {}
51 } 51 // }
52 } else if *self == Self::Subscriptions || *self == Self::Library { 52 // }
53 // match page { 53 // }
54 // Page::MainMenu(MainMenuPage::Subscriptions) => *self = Self::Subscriptions,
55 // Page::MainMenu(MainMenuPage::Library) => *self = Self::Library,
56 // _ => {}
57 // }
58 }
59 }
60} 54}
61 55
62impl ToString for PageButton { 56impl ToString for PageButton {
@@ -75,14 +69,15 @@ impl ToString for PageButton {
75} 69}
76 70
77impl FrameworkItem for PageButton { 71impl FrameworkItem for PageButton {
78 fn load_item( 72 // fn load_item(
79 &mut self, 73 // &mut self,
80 framework: &mut tui_additions::framework::FrameworkClean, 74 // framework: &mut tui_additions::framework::FrameworkClean,
81 _info: tui_additions::framework::ItemInfo, 75 // _info: tui_additions::framework::ItemInfo,
82 ) -> Result<(), Box<dyn std::error::Error>> { 76 // ) -> Result<(), Box<dyn std::error::Error>> {
83 self.update_toggleable(framework.data.state.get::<Page>().unwrap()); 77 // self.update_toggleable(framework.data.state.get::<Page>().unwrap());
84 Ok(()) 78 // Ok(())
85 } 79 // }
80
86 // it is basically a paragraph (text) with borders 81 // it is basically a paragraph (text) with borders
87 fn render( 82 fn render(
88 &mut self, 83 &mut self,
@@ -122,19 +117,12 @@ impl FrameworkItem for PageButton {
122 let current_page = framework.data.state.get::<Page>().unwrap(); 117 let current_page = framework.data.state.get::<Page>().unwrap();
123 let self_page = self.page(current_page); 118 let self_page = self.page(current_page);
124 119
125 if self_page == *current_page { 120 // if self_page == *current_page {
126 match self { 121 // match self {
127 Self::Trending => *self = Self::Popular, 122 // Self::Trending => *self = Self::Popular,
128 Self::Popular => *self = Self::Trending, 123 // Self::Popular => *self = Self::Trending,
129 // Self::Subscriptions => *self = Self::Library, 124 // }
130 // Self::Library => *self = Self::Subscriptions, 125 // }
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 }
138 126
139 framework 127 framework
140 .data 128 .data