Commit 772a217411

772a2174114868bb4b2c7b689be7a863fd04692e

parent: f3b1912e0d

Unsigned

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

subscriptions system finished, 0.7.2

Layout: unified · split

Cargo.lock +8 −1
@@ -1243,6 +1243,12 @@ version = "0.2.8"
12431243source = "registry+https://github.com/rust-lang/crates.io-index"
12441244checksum = "1865806a559042e51ab5414598446a5871b561d21b6764f2eabb0dd481d880a6"
12451245
1246[[package]]
1247name = "urlencoding"
1248version = "2.1.2"
1249source = "registry+https://github.com/rust-lang/crates.io-index"
1250checksum = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9"
1251
12461252[[package]]
12471253name = "vcpkg"
12481254version = "0.2.15"
@@ -1546,7 +1552,7 @@ dependencies = [
15461552
15471553[[package]]
15481554name = "youtube-tui"
1549version = "0.7.1"
1555version = "0.7.2"
15501556dependencies = [
15511557 "chrono",
15521558 "clipboard",
@@ -1560,6 +1566,7 @@ dependencies = [
15601566 "tui",
15611567 "tui-additions",
15621568 "typemap",
1569 "urlencoding",
15631570 "viuer",
15641571]
15651572
Cargo.toml +5 −1
@@ -1,6 +1,6 @@
11[package]
22name = "youtube-tui"
3version = "0.7.1"
3version = "0.7.2"
44authors = ["Siriusmart <siriusmart@tuta.io>"]
55edition = "2021"
66description = "An aesthetically pleasing YouTube TUI written in Rust"
@@ -35,6 +35,10 @@ serde_yaml = {version = "0.9", default-features = false}
3535dyn-clone = {version = "1.0", default-features = false}
3636serde_json = {version = "1.0", default-features = false}
3737clipboard = {version = "0.5", optional = true}
38urlencoding = "2.1"
3839
3940# tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]}
4041# invidious = {path = "../../Rust/Packages/invidious"}
42
43[package.metadata.docs.rs]
44no-default-features = true
README.md +4 −2
@@ -63,11 +63,13 @@ It also includes features like:
6363- Mouse support
6464- Extensible keybindings system
6565- Offline library
66- Subscriptions
6667
6768### What it doesn't have
6869
69- Subscriptions (first priority)
70- Clipboard feature that does not depend on the `clipboard` feature
70- [URGENT] Replace the no-longer-going-to-compile `typemap` dependency with either a self implementation of it or a useable crate.
71- Strip down some libraries to reduce compile speed.
72- Add command section for channel main page (first priority)
7173- Up arrow command history + Ctrl arrow keys move between words
7274
7375## How to contribute
docs/src/README.md +4 −2
@@ -56,11 +56,13 @@ It also includes features like:
5656- Mouse support
5757- Extensible keybindings system
5858- Offline library
59- Subscriptions
5960
6061### What it doesn't have
6162
62- Subscriptions (first priority)
63- Clipboard feature that does not depend on the `clipboard` feature
63- [URGENT] Replace the no-longer-going-to-compile `typemap` dependency with either a self implementation of it or a useable crate.
64- Strip down some libraries to reduce compile speed.
65- Add command section for channel main page (first priority)
6466- Up arrow command history + Ctrl arrow keys move between words
6567
6668## How to contribute
docs/src/SUMMARY.md +1 −1
@@ -20,7 +20,7 @@
2020
2121- [How it works](explaination/how_it_works.md)
2222 - [Framework](explaination/framework.md)
23 - [Event loop]()
23 - [Event loop](explaination/event-loop.md)
2424 - [Invidious and loading videos]()
2525 - [Caching and library]()
2626
docs/src/basic_usage.md +6
@@ -49,6 +49,12 @@ To apply search filters, select the button with 3 dots (`...`) to the right of t
4949
5050Press `Enter` to select a video or playlist from any lists, then move the cursor to the *bottom item* where you can play, download and open the webpage in browser.
5151
52## Feeds
53
54Feeds allows you to view updates from subscribed channels, similar to how subscriptions works on YouTube.
55
56![](./images/feed-showcase.png)
57
5258## Command mode
5359
5460Command mode is like that of Vim, it can be started by pressing `:` when nothing is selected.
docs/src/changelogs.md +13 −2
@@ -1,13 +1,24 @@
11# Changelogs
22
3## v0.7.1
3## v0.7.2
44
55### Added
66
7- Feeds page, and the subscriptions system.
8- Reduced compile time needed by a lot.
9
10### Fixed
11
12- I remember fixing something but forgot what it was D:
13
14### v0.7.1
15
16#### Added
17
718- Options for config loading. (`write_config` in `main.yml`)
819- Parrallel/blocking commands `parrun`/`run`
920
10### Fixed
21#### Fixed
1122
1223- Fixed crashing when launching without permissions to write to config files (<a href="https://github.com/Siriusmart/youtube-tui/issues/29" target=_blank>issue 29</a>)
1324
docs/src/commands.md +6 −3
@@ -53,9 +53,12 @@ parrun [command]
5353## Library
5454
5555```vim
56bookmark [id]
57unmark [id]
58togglemark [id]
56bookmark [id] Bookmark item with ID (item must be already loaded)
57unmark [id] Remove bookmark item with ID
58togglemark [id] Toggle bookmark status
59sub/sync [id or url] Add channel to subscription, or sync an existing channel
60unsub [id or url] Remove channel from subscription
61syncall Sync all subscriptions
5962```
6063
6164## Text commands
docs/src/config/commands.md +4
@@ -83,4 +83,8 @@ Does not include custom env set in `main.yml`.
8383|`embed-url`|video|String url to the embed video (required to play video using mpv from Invidious)|
8484|`all-videos`|playlist|String url***s*** separated by space to all embed videos in a playlist|
8585|`hover-url`|trending, popular, search|Url of the currenly hovering item.|
86|`hover-channel-url`|feed|Url of the currenly hovering channel.|
87|`hover-channel-id`|feed|ID of the currenly hovering channel.|
88|`hover-video-url`|feed|Url of the currenly hovering video.|
89|`hover-video-id`|feed|ID of the currenly hovering video.|
8690|`all-ids`|playlist|IDs of all videos in a playlist, separated with space.|
docs/src/explaination/event-loop.md added +41
@@ -0,0 +1,41 @@
1# Event loop
2
3The event loop is like the glue that puts everything together.
4
5## Before the event loop
6
7But before the TUI enters it's main event loop, it does several things.
8
9### 1. Check what command is being ran.
10
11If the command does not need to enter the main TUI, don't enter the main TUI.
12
13For example, `help` or `version` just returns a text message on your terminal screen. In [`main.rs`](https://github.com/Siriusmart/youtube-tui/blob/f3b1912e0d99b46fd8c7b0be2a1606a7b087b650/src/main.rs#LL19C1-L19C43) line 19, it is checked whether the entered command is a valid text command. If so, the program exits without ever reaching the TUI code.
14
15### 2. Enable raw mode
16
17If you've tried killing youtube-tui while it's running (`killall youtube-tui`), your terminal should be in a weird state - where everything, including mouse movement seem to be captured. That's the raw mode.
18
19I have no idea what is special about it, but it is in the examples of `tui-rs` [here](https://github.com/fdehau/tui-rs/blob/fafad6c96109610825aad89c4bba5253e01101ed/examples/block.rs#L18) (one of the main dependency of this TUI).
20
21### 3. Init
22
23There are a bunch of things happening in this stage, but it really just boils down to a few basic things:
24
25- Reading/creating config files, subscriptions, libraries and inserting them to the *pool of shared data* (global data) within the [framework](https://docs.rs/tui-additions/0.1.13/tui_additions/framework/struct.Framework.html) struct.
26
27Global data is used here, the reason should be obvious. All pages, should share the same config, there is no need to keep extra copies of the (usually) same thing and waste memory.
28
29- Insert some structs needed for the TUI to run.
30
31These structs includes [`Message`](https://github.com/Siriusmart/youtube-tui/blob/master/src/global/structs/message.rs) storing the message to be displayed in message bar, and [`Status`](https://github.com/Siriusmart/youtube-tui/blob/master/src/global/structs/status.rs), useful for storing all sorts of values, for example helping with the running (mostly rendering) of the TUI.
32
33- Move some files
34
35Some files have to be moved to `~/.cache/youtube-tui/` from (usually) `~/.local/share/youtube-tui/` for stored content to be used by the TUI, this is why running multiple instances of the program can mess things up - as one instance exits the files got moved from `.cache` to `.local`, and the other instance no longer sees the files they thought was still in `.cache`.
36
37> The full init code is [here](https://github.com/Siriusmart/youtube-tui/blob/master/src/init.rs)
38
39---
40
41todo...
docs/src/explaination/framework.md +4 −2
@@ -36,14 +36,16 @@ Instead of using a `HashMap<(usize, usize)>`, using a 2D array ensures that all
3636
3737## Data
3838
39There are 2 sets of data available - *global* and *state*.
39There are 2 pools of data available - *global* and *state*.
4040
4141**Global data** are global across all pages, this is mainly used to store config structs, as they are meant to be applied globally.
4242
43**State data** are exclusive to each page, this is done to ensure that each page will get the correct data.
43**State data** are exclusive to each page, this is done to ensure that each page will get the correct data.
4444
4545> For example, if state data is not used, the next page will overwrite data in the previous page, making going back in history impossible.
4646
47[This](https://github.com/Siriusmart/tui-additions/blob/3087abbf8e121f26c0956cda5fb43efc7b862bc7/src/framework/framework.rs#LL39C4-L39C4) showed how state data stays with the history *snapshot* of the page, whereas global data does not.
48
4749## History
4850
4951This stores the past states and data of the struct, pretty self explanatory.
docs/src/images/feed-showcase.png added

Binary file not shown.

docs/src/installation.md +3 −1
@@ -28,8 +28,10 @@ yay -S youtube-tui-git # latest git version, potentially untested
2828yay -S youtube-tui-full-bin # default binary (out of date)
2929yay -S youtube-tui-nodefaults-bin # minimal binary (out of date)
3030```
31## Installation on NixOS
31## Installation on NixOS (recommended)
32
3233Add the following Nix code to your NixOS Configuration
34
3335```nix
3436environment.systemPackages = [
3537 pkgs.youtube-tui
src/config/commandbindings.rs +22 −8
@@ -19,7 +19,7 @@ pub struct CommandBindings {
1919 pub channel_videos: HashMap<KeyCode, HashMap<u8, String>>,
2020 pub channel_playlists: HashMap<KeyCode, HashMap<u8, String>>,
2121 pub watchhistory: HashMap<KeyCode, HashMap<u8, String>>,
22 pub subscriptions: HashMap<KeyCode, HashMap<u8, String>>,
22 pub feed: HashMap<KeyCode, HashMap<u8, String>>,
2323 pub libray: HashMap<KeyCode, HashMap<u8, String>>,
2424}
2525
@@ -41,7 +41,7 @@ impl CommandBindings {
4141 Page::MainMenu(MainMenuPage::Popular) => get_command(key, &self.popular),
4242 Page::MainMenu(MainMenuPage::History) => get_command(key, &self.watchhistory),
4343 Page::MainMenu(MainMenuPage::Library) => get_command(key, &self.libray),
44 Page::Subscriptions(_) => get_command(key, &self.subscriptions),
44 Page::Feed => get_command(key, &self.feed),
4545 Page::SingleItem(SingleItemPage::Video(_)) => get_command(key, &self.video),
4646 Page::SingleItem(SingleItemPage::Playlist(_)) => get_command(key, &self.playlist),
4747 Page::ChannelDisplay(ChannelDisplayPage {
@@ -91,8 +91,8 @@ pub struct CommandBindingsSerde {
9191 pub channel_playlists: HashMap<KeyCodeSerde, HashMap<u8, String>>,
9292 #[serde(default = "watchhistory_default")]
9393 pub watchhistory: HashMap<KeyCodeSerde, HashMap<u8, String>>,
94 #[serde(default = "subscriptions_default")]
95 pub subscriptions: HashMap<KeyCodeSerde, HashMap<u8, String>>,
94 #[serde(default = "feed_default")]
95 pub feed: HashMap<KeyCodeSerde, HashMap<u8, String>>,
9696 #[serde(default = "library_default")]
9797 pub library: HashMap<KeyCodeSerde, HashMap<u8, String>>,
9898}
@@ -114,7 +114,7 @@ impl CommandBindingsSerde {
114114 video: de_serde(self.video)?,
115115 trending: de_serde(self.trending)?,
116116 watchhistory: de_serde(self.watchhistory)?,
117 subscriptions: de_serde(self.subscriptions)?,
117 feed: de_serde(self.feed)?,
118118 libray: de_serde(self.library)?,
119119 })
120120 }
@@ -133,7 +133,7 @@ impl Default for CommandBindingsSerde {
133133 video: video_default(),
134134 trending: trending_default(),
135135 watchhistory: watchhistory_default(),
136 subscriptions: subscriptions_default(),
136 feed: feed_default(),
137137 library: library_default(),
138138 }
139139 }
@@ -238,8 +238,22 @@ fn watchhistory_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
238238 ])
239239}
240240
241fn subscriptions_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
242 HashMap::default()
241fn feed_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
242 HashMap::from([
243 (
244 KeyCodeSerde::Char('a'),
245 HashMap::from([(
246 2,
247 String::from("parrun ${terminal-emulator} mpv '${hover-video-url}' --no-video"),
248 )]),
249 ),
250 (KeyCodeSerde::Char('A'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-channel-url}/videos' --no-video --loop-playlist=inf --shuffle"))])),
251 (KeyCodeSerde::Char('P'), HashMap::from([(1, String::from("parrun ${terminal-emulator} mpv '${hover-channel-url}/videos' --no-video --loop-playlist=inf --shuffle"))])),
252 (
253 KeyCodeSerde::Char('p'),
254 HashMap::from([(2, String::from("parrun mpv '${hover-video-url}'"))]),
255 ),
256 ])
243257}
244258
245259fn library_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
src/config/commands.rs +16
@@ -110,6 +110,10 @@ fn video_default() -> Vec<HashMap<String, String>> {
110110 String::from("View channel"),
111111 String::from("channel ${channel-id}"),
112112 )]),
113 HashMap::from([(
114 String::from("Subscribe to channel"),
115 String::from("sync ${channel-id}"),
116 )]),
113117 HashMap::from([(
114118 String::from("Open in browser"),
115119 String::from("parrun ${browser} '${url}'"),
@@ -155,6 +159,10 @@ fn saved_video_default() -> Vec<HashMap<String, String>> {
155159 String::from("View channel"),
156160 String::from("channel ${channel-id}"),
157161 )]),
162 HashMap::from([(
163 String::from("Subscribe to channel"),
164 String::from("sync ${channel-id}"),
165 )]),
158166 HashMap::from([(
159167 String::from("Open in browser"),
160168 String::from("parrun ${browser} '${url}'"),
@@ -201,6 +209,10 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
201209 String::from("View channel"),
202210 String::from("channel ${channel-id}"),
203211 )]),
212 HashMap::from([(
213 String::from("Subscribe to channel"),
214 String::from("sync ${channel-id}"),
215 )]),
204216 HashMap::from([(
205217 String::from("Open in browser"),
206218 String::from("parrun ${browser} '${url}'"),
@@ -247,6 +259,10 @@ fn saved_playlist_default() -> Vec<HashMap<String, String>> {
247259 String::from("View channel"),
248260 String::from("channel ${channel-id}"),
249261 )]),
262 HashMap::from([(
263 String::from("Subscribe to channel"),
264 String::from("sync ${channel-id}"),
265 )]),
250266 HashMap::from([(
251267 String::from("Open in browser"),
252268 String::from("parrun ${browser} '${url}'"),
src/config/pages.rs +24 −25
@@ -28,8 +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,
31 #[serde(default = "feed_default")]
32 pub feed: PageConfig,
3333 #[serde(default = "search_default")]
3434 pub search: PageConfig,
3535 #[serde(default = "singleitem_default")]
@@ -50,7 +50,7 @@ impl Default for PagesConfig {
5050 fn default() -> Self {
5151 Self {
5252 main_menu: main_menu_default(),
53 subscriptions: subscriptions_default(),
53 feed: feed_default(),
5454 search: search_default(),
5555 singleitem: singleitem_default(),
5656 channeldisplay: channeldisplay_default(),
@@ -167,12 +167,14 @@ pub enum PageItems {
167167 Popular,
168168 /// the history button which loads the watch history page
169169 History,
170 /// the subscriptions button which loads the subscriptions page
171 Subscriptions,
170 /// the feed button which loads the feed page
171 Feed,
172172 /// the library button which loads the saved page
173173 Library,
174 /// Subscriptions list (channels)
174 /// Feed list (channels)
175175 ChannelList,
176 /// Feed list (videos)
177 VideoList,
176178 /// the search filters `...` button, displays a popup when selected
177179 SearchFilters,
178180 /// playlist and video info display
@@ -195,9 +197,10 @@ impl PageItems {
195197 Self::Popular => Box::new(PageButton::Popular),
196198 Self::Trending => Box::new(PageButton::Trending),
197199 Self::History => Box::new(PageButton::History),
198 Self::Subscriptions => Box::new(PageButton::Subscriptions),
200 Self::Feed => Box::new(PageButton::Feed),
199201 Self::Library => Box::new(PageButton::Library),
200202 Self::ChannelList => Box::<ChannelList>::default(),
203 Self::VideoList => Box::<VideoList>::default(),
201204 Self::MessageBar => Box::<MessageBar>::default(),
202205 Self::ItemList => Box::<ItemList>::default(),
203206 Self::SearchFilters => Box::<SearchFilter>::default(),
@@ -214,16 +217,18 @@ impl PageItems {
214217 Self::Popular
215218 | Self::Trending
216219 | Self::History
217 | Self::Subscriptions
220 | Self::Feed
218221 | Self::Library
219222 | Self::ChannelMain
220223 | Self::ChannelVideos
221224 | Self::ChannelPlaylists => Constraint::Length(15),
222225 Self::SearchBar => Constraint::Min(16),
223226 Self::MessageBar => Constraint::Min(3),
224 Self::ItemList | Self::SingleItemInfo | Self::ChannelDisplay | Self::ChannelList => {
225 Constraint::Min(9)
226 }
227 Self::ItemList
228 | Self::SingleItemInfo
229 | Self::ChannelDisplay
230 | Self::ChannelList
231 | Self::VideoList => Constraint::Min(9),
227232 Self::SearchFilters => Constraint::Length(5),
228233 }
229234 }
@@ -232,7 +237,7 @@ impl PageItems {
232237 match self {
233238 Self::Popular
234239 | Self::History
235 | Self::Subscriptions
240 | Self::Feed
236241 | Self::Library
237242 | Self::ChannelMain
238243 | Self::ChannelVideos
@@ -241,9 +246,10 @@ impl PageItems {
241246 | Self::MessageBar
242247 | Self::SearchBar
243248 | Self::SearchFilters => Constraint::Length(3),
244 Self::ItemList | Self::SingleItemInfo | Self::ChannelDisplay | Self::ChannelList => {
249 Self::ItemList | Self::SingleItemInfo | Self::ChannelDisplay | Self::VideoList => {
245250 Constraint::Min(6)
246251 }
252 Self::ChannelList => Constraint::Length(18),
247253 }
248254 }
249255}
@@ -277,11 +283,7 @@ fn main_menu_default() -> PageConfig {
277283 layout: vec![
278284 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
279285 PageRow::from_vec(
280 vec![
281 PageItems::Library,
282 PageItems::Subscriptions,
283 PageItems::History,
284 ],
286 vec![PageItems::Library, PageItems::Feed, PageItems::History],
285287 true,
286288 ),
287289 PageRow::from_vec(vec![PageItems::ItemList], false),
@@ -332,21 +334,18 @@ fn channeldisplay_default() -> PageConfig {
332334 }
333335}
334336
335fn subscriptions_default() -> PageConfig {
337fn feed_default() -> PageConfig {
336338 PageConfig {
337339 layout: vec![
338340 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
339341 PageRow::from_vec(
340 vec![
341 PageItems::Library,
342 PageItems::Subscriptions,
343 PageItems::History,
344 ],
342 vec![PageItems::Library, PageItems::Feed, PageItems::History],
345343 true,
346344 ),
347345 PageRow::from_vec(vec![PageItems::ChannelList], false),
346 PageRow::from_vec(vec![PageItems::VideoList], false),
348347 PageRow::from_vec(vec![PageItems::MessageBar], false),
349348 ],
350 message: String::from("Loading subscriptions..."),
349 message: String::from("Loading feed..."),
351350 }
352351}
src/exit.rs +3 −6
@@ -15,12 +15,9 @@ pub fn exit(framework: &Framework) -> Result<(), Box<dyn Error>> {
1515 .get::<WatchHistory>()
1616 .unwrap()
1717 .exit_move();
18 framework
19 .data
20 .global
21 .get::<Subscriptions>()
22 .unwrap()
23 .exit_move();
18 let subscriptions = framework.data.global.get::<Subscriptions>().unwrap();
19 subscriptions.exit_move();
20 subscriptions.save()?;
2421 framework.data.global.get::<Library>().unwrap().exit_move();
2522
2623 let home_dir = home_dir().unwrap();
src/global/functions/run_command.rs +55 −8
@@ -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" | "subs" => Some(Page::Subscriptions(None)),
127 "feed" => Some(Page::Feed),
128128 "library" => Some(Page::MainMenu(MainMenuPage::Library)),
129129 "channel" => {
130130 if command.len() == 2 {
@@ -212,9 +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"] | ["subs"] => {
216 run_single_command(&["loadpage", "subscriptions"], framework, terminal)
217 }
215 ["feed"] => run_single_command(&["loadpage", "feed"], framework, terminal),
218216 ["bookmarks"] => run_single_command(&["loadpage", "bookmarks"], framework, terminal),
219217 ["library"] => run_single_command(&["loadpage", "library"], framework, terminal),
220218 ["search"] => run_single_command(&["loadpage", "search"], framework, terminal),
@@ -345,7 +343,7 @@ pub fn run_single_command(
345343 *framework.data.global.get_mut::<Message>().unwrap() =
346344 Message::Success(String::from("Copied to clipboad"));
347345 }
348 ["sub", identifier] => {
346 ["sub", identifier] | ["sync", identifier] => {
349347 let id = if identifier.len() == 24 {
350348 identifier.to_string()
351349 } else {
@@ -376,7 +374,6 @@ pub fn run_single_command(
376374 *framework.data.global.get_mut::<Message>().unwrap() =
377375 Message::Message(String::from("Syncing..."));
378376 terminal.draw(|frame| framework.render(frame)).unwrap();
379 framework.render(&mut terminal.get_frame());
380377
381378 let subscriptions = framework.data.global.get_mut::<Subscriptions>().unwrap();
382379 match subscriptions.sync_one(&id, &client, image_index, download_thumbnails) {
@@ -389,6 +386,13 @@ pub fn run_single_command(
389386 Message::Error(format!("Sync failed: {e}"));
390387 }
391388 };
389 framework
390 .data
391 .state
392 .get_mut::<Tasks>()
393 .unwrap()
394 .priority
395 .push(Task::RenderAll);
392396 }
393397 ["unsub", identifier] => {
394398 let id = if identifier.len() == 24 {
@@ -421,6 +425,47 @@ pub fn run_single_command(
421425 *framework.data.global.get_mut::<Message>().unwrap() =
422426 Message::Error(String::from("Channel not found in subscriptions"));
423427 }
428 framework
429 .data
430 .state
431 .get_mut::<Tasks>()
432 .unwrap()
433 .priority
434 .push(Task::RenderAll);
435 }
436 ["syncall"] => {
437 *framework.data.global.get_mut::<Message>().unwrap() =
438 Message::Message(String::from("Syncing..."));
439 terminal.draw(|frame| framework.render(frame)).unwrap();
440
441 let client = framework
442 .data
443 .global
444 .get::<InvidiousClient>()
445 .unwrap()
446 .clone();
447 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
448 let image_index = mainconfig.image_index;
449 let download_thumbnails = mainconfig.images.display();
450
451 let (success, failed) = framework
452 .data
453 .global
454 .get_mut::<Subscriptions>()
455 .unwrap()
456 .sync(&client, image_index, download_thumbnails);
457
458 *framework.data.global.get_mut::<Message>().unwrap() = Message::Success(format!(
459 "Subscriptions synced: {success} success | {failed} fail"
460 ));
461
462 framework
463 .data
464 .state
465 .get_mut::<Tasks>()
466 .unwrap()
467 .priority
468 .push(Task::RenderAll);
424469 }
425470 _ => {
426471 *framework.data.global.get_mut::<Message>().unwrap() =
@@ -479,6 +524,7 @@ const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
479524 \x1b[33mloadpage subscriptions\x1b[0m Loads the subscriptions page
480525 \x1b[33mloadpage bookmarks\x1b[0m Loads the bookmarks page
481526 \x1b[33mloadpage library\x1b[0m Loads the library (saved items) page
527 \x1b[33mloadpage feed\x1b[0m Loads the library (feed) page
482528 \x1b[33mloadpage search [query]\x1b[0m Loads the search page with the given query
483529 \x1b[33mloadpage video [identifier]\x1b[0m Loads the video item page
484530 \x1b[33mloadpage playlist [identifier]\x1b[0m Loads the playlist item page
@@ -501,8 +547,9 @@ const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
501547 \x1b[33mbookmark [id]\x1b[0m Bookmark item with ID (item must be already loaded)
502548 \x1b[33munmark [id]\x1b[0m Remove bookmark item with ID
503549 \x1b[33mtogglemark [id]\x1b[0m Toggle bookmark status
504 \x1b[33msub [id or url]\x1b[0m Add channel to subscription
550 \x1b[33msub/sync [id or url]\x1b[0m Add channel to subscription, or sync an existing channel
505551 \x1b[33munsub [id or url]\x1b[0m Remove channel from subscription
552 \x1b[33msyncall\x1b[0m Sync all subscriptions
506553
507554\x1b[91mALT:\x1b[0m
508555\x1b[37malts links back to the original command\x1b[30m
@@ -513,4 +560,4 @@ const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
513560 \x1b[33mq, exit, x\x1b[0m `quit`
514561 \x1b[33mcp [text]\x1b[0m `copy [text]`
515562
516\x1b[37mOnly load page and informational commands can be used from command line, the rest can only be used in (`:`) command mode inside the TUI.\x1b[0m";
563\x1b[37mOnly load page and informational commands should be used from command line, the rest can only be used in (`:`) command mode inside the TUI.\x1b[0m";
src/global/functions/update_provider.rs +1 −1
@@ -66,7 +66,7 @@ pub fn update_provider(data: &mut FrameworkData) {
6666 }
6767 },
6868 )],
69 Page::Subscriptions(_) => vec![(
69 Page::Feed => 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 +27 −2
@@ -40,7 +40,7 @@ impl CollectionItem for Item {
4040}
4141
4242/// stores information of a previewed video
43#[derive(Clone, Serialize, Deserialize)]
43#[derive(Clone, Serialize, Deserialize, Eq)]
4444pub struct MiniVideoItem {
4545 pub title: String,
4646 pub id: String,
@@ -50,10 +50,30 @@ pub struct MiniVideoItem {
5050 pub channel: String,
5151 pub channel_id: String,
5252 pub published: Option<String>,
53 pub timestamp: Option<u64>,
5354 pub description: Option<String>,
5455}
5556
56unsafe impl Send for MiniVideoItem {}
57impl PartialOrd for MiniVideoItem {
58 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
59 other.timestamp.partial_cmp(&self.timestamp)
60 // self.timestamp.partial_cmp(&other.timestamp)
61 }
62}
63
64impl Ord for MiniVideoItem {
65 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
66 self.timestamp
67 .unwrap_or_default()
68 .cmp(&other.timestamp.unwrap_or_default())
69 }
70}
71
72impl PartialEq for MiniVideoItem {
73 fn eq(&self, other: &Self) -> bool {
74 self.id == other.id
75 }
76}
5777
5878/// stores information of a previewed playlist
5979#[derive(Clone, Serialize, Deserialize)]
@@ -288,6 +308,7 @@ impl Item {
288308 views: Some(viewcount_text(original.views)),
289309 channel: original.author,
290310 channel_id: original.author_id,
311 timestamp: Some(original.published),
291312 published: Some(format!(
292313 "{} [{}]",
293314 original.published_text,
@@ -307,6 +328,7 @@ impl Item {
307328 views: Some(viewcount_text(original.views)),
308329 channel: original.author,
309330 channel_id: original.author_id,
331 timestamp: Some(original.published),
310332 published: Some(format!(
311333 "{} [{}]",
312334 original.published_text,
@@ -351,6 +373,7 @@ impl Item {
351373 views: Some(viewcount_text(views)),
352374 channel: author,
353375 channel_id: author_id,
376 timestamp: Some(published),
354377 published: Some(format!("{} [{}]", published_text, date_text(published))),
355378 description: Some(description),
356379 }),
@@ -442,6 +465,7 @@ impl Item {
442465 views: None,
443466 channel: original.author,
444467 channel_id: original.author_id,
468 timestamp: None,
445469 published: None,
446470 description: None,
447471 })
@@ -472,6 +496,7 @@ impl Item {
472496 views: Some(viewcount_text(original.view_count)),
473497 channel: original.author,
474498 channel_id: original.author_id,
499 timestamp: Some(original.published),
475500 published: Some(format!(
476501 "{} [{}]",
477502 original.published_text,
src/global/structs/page.rs +4 −4
@@ -10,7 +10,7 @@ use typemap::Key;
1010pub enum Page {
1111 MainMenu(MainMenuPage),
1212 // Option<new channel selected index>
13 Subscriptions(Option<usize>),
13 Feed,
1414 Search(Search),
1515 SingleItem(SingleItemPage),
1616 ChannelDisplay(ChannelDisplayPage),
@@ -22,7 +22,7 @@ impl Debug for Page {
2222 "{}(_)",
2323 match self {
2424 Self::MainMenu(_) => "MainMenu",
25 Self::Subscriptions(_) => "Subscriptions",
25 Self::Feed => "Feed",
2626 Self::Search(_) => "Search",
2727 Self::SingleItem(_) => "SingleItem",
2828 Self::ChannelDisplay(_) => "ChannelDisplay",
@@ -92,7 +92,7 @@ impl Page {
9292 let pages_config = framework.data.global.get::<PagesConfig>().unwrap();
9393 match self {
9494 Self::MainMenu(_) => pages_config.main_menu.clone(),
95 Self::Subscriptions(_) => pages_config.subscriptions.clone(),
95 Self::Feed => pages_config.feed.clone(),
9696 Self::Search(_) => pages_config.search.clone(),
9797 Self::SingleItem(_) => pages_config.singleitem.clone(),
9898 Self::ChannelDisplay(_) => pages_config.channeldisplay.clone(),
@@ -104,7 +104,7 @@ impl Page {
104104 let pages_config = framework.data.global.get::<PagesConfig>().unwrap();
105105 match self {
106106 Self::MainMenu(_) => pages_config.main_menu.message.clone(),
107 Self::Subscriptions(_) => pages_config.subscriptions.message.clone(),
107 Self::Feed => pages_config.feed.message.clone(),
108108 Self::Search(_) => pages_config.search.message.clone(),
109109 Self::SingleItem(_) => pages_config.singleitem.message.clone(),
110110 Self::ChannelDisplay(_) => pages_config.channeldisplay.message.clone(),
src/global/structs/status.rs +4 −1
@@ -1,6 +1,6 @@
11use tui::layout::Rect;
22use tui_additions::widgets::TextField;
3use typemap::Key;
3use typemap::{CloneMap, Key, TypeMap};
44
55use crate::config::Provider;
66
@@ -23,6 +23,8 @@ pub struct Status {
2323 pub provider: Provider,
2424 /// if provider is updated, lasts for 1 event loop
2525 pub provider_updated: bool,
26 /// storage that is cleared every event loop
27 pub storage: CloneMap,
2628}
2729
2830impl Key for Status {
@@ -40,6 +42,7 @@ impl Default for Status {
4042 prev_frame: None,
4143 provider: Provider::YouTube,
4244 provider_updated: false,
45 storage: TypeMap::custom(),
4346 }
4447 }
4548}
src/global/structs/subscriptions.rs +43 −9
@@ -34,6 +34,7 @@ impl Subscriptions {
3434 let failed = Arc::new(AtomicU32::new(0));
3535 let success = Arc::new(AtomicU32::new(0));
3636
37 let len = self.0.len();
3738 let (tx, rx) = mpsc::channel();
3839 let mut channels = Vec::new();
3940 std::mem::swap(&mut self.0, &mut channels);
@@ -59,7 +60,7 @@ impl Subscriptions {
5960 });
6061 });
6162
62 for item in rx {
63 for item in rx.into_iter().take(len) {
6364 self.0.push(item);
6465 }
6566
@@ -83,7 +84,11 @@ impl Subscriptions {
8384 let synced = sync_one(id, client, image_index, download_thumbnails)?;
8485 for item in self.0.iter_mut() {
8586 if *item == synced {
86 *item = synced;
87 *item = SubItem {
88 // synced.has_new = !synced.videos.is_empty
89 has_new: synced.has_new && synced.videos.first() != item.videos.first(),
90 ..synced
91 };
8792 return Ok(());
8893 }
8994 }
@@ -103,6 +108,20 @@ impl Subscriptions {
103108
104109 false
105110 }
111
112 pub fn get_all_videos(&self) -> Vec<MiniVideoItem> {
113 let mut videos = self
114 .0
115 .iter()
116 .flat_map(|item| item.videos.clone())
117 .collect::<Vec<_>>();
118 videos.sort();
119 videos
120 }
121
122 pub fn get_channels(&self) -> Vec<FullChannelItem> {
123 self.0.iter().map(|item| item.channel.clone()).collect()
124 }
106125}
107126
108127fn sync_one(
@@ -123,10 +142,8 @@ fn sync_one(
123142 .map(|channel| Item::from_full_channel(channel, image_index).into_fullchannel())
124143 .ok(),
125144 )
126 .unwrap();
127145 });
128
129 let videos = client
146 let mut videos = client
130147 .0
131148 .channel_videos(id, None)?
132149 .videos
@@ -137,6 +154,7 @@ fn sync_one(
137154 .unwrap()
138155 })
139156 .collect::<Vec<_>>();
157 videos.sort();
140158
141159 let channel = rx
142160 .recv()
@@ -165,13 +183,20 @@ fn sync_one(
165183 });
166184 }
167185
168 Ok(SubItem { channel, videos })
186 Ok(SubItem {
187 channel,
188 has_new: !videos.is_empty(),
189 videos,
190 last_sync: chrono::Utc::now().timestamp() as u64,
191 })
169192}
170193
171194#[derive(Clone, Serialize, Deserialize)]
172195pub struct SubItem {
173196 pub channel: FullChannelItem,
174197 pub videos: Vec<MiniVideoItem>,
198 pub last_sync: u64,
199 pub has_new: bool,
175200}
176201
177202impl Eq for SubItem {}
@@ -195,7 +220,11 @@ impl PartialEq for SubItem {
195220
196221impl PartialOrd for SubItem {
197222 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
198 self.channel.name.partial_cmp(&other.channel.name)
223 let get_timestamp = |item: &Self| match item.videos.first() {
224 Some(video) => video.timestamp.unwrap(),
225 None => 0,
226 };
227 get_timestamp(other).partial_cmp(&get_timestamp(self))
199228 }
200229}
201230
@@ -253,14 +282,19 @@ impl Collection<SubItem> for Subscriptions {
253282
254283 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
255284 // which case returns Self::default()
256 if let Ok(subs) = res {
285 if let Ok(mut subs) = res {
286 subs.0.sort();
257287 subs
258288 } else {
259289 // if the file does exist, back it up
260290 // if it doesn't exist, it will throw an error but we dont care
261291 let mut new_path = path.clone();
262292 new_path.pop();
263 new_path.push(format!("index-{}.json", chrono::offset::Local::now(),));
293 new_path.push(format!(
294 "{}.{}.old",
295 Self::INDEX_PATH,
296 chrono::offset::Local::now()
297 ));
264298 let _ = fs::rename(&path, &new_path);
265299
266300 Self::default()
src/global/traits/collection.rs +5 −1
@@ -100,7 +100,11 @@ where
100100 // if it doesn't exist, it will throw an error but we dont care
101101 let mut new_path = path.clone();
102102 new_path.pop();
103 new_path.push(format!("index-{}.json", chrono::offset::Local::now(),));
103 new_path.push(format!(
104 "{}.{}.old",
105 Self::INDEX_PATH,
106 chrono::offset::Local::now()
107 ));
104108 let _ = fs::rename(&path, &new_path);
105109
106110 Vec::new()
src/items/channellist.rs +296 −30
@@ -1,19 +1,28 @@
11use crossterm::event::KeyCode;
2use tui::{layout::Constraint, style::Style};
2use tui::{
3 layout::{Constraint, Rect},
4 style::Style,
5 widgets::Paragraph,
6};
37use tui_additions::{
4 framework::FrameworkItem,
8 framework::{FrameworkClean, FrameworkItem},
59 widgets::{Grid, TextList},
610};
11use typemap::Key;
712
8use crate::{config::AppearanceConfig, global::structs::*};
13use crate::{
14 config::{AppearanceConfig, MainConfig, Provider},
15 global::{functions::set_envs, structs::*},
16};
917
10use super::ItemInfo;
18use super::{ItemInfo, VidSelect};
1119
1220#[derive(Clone)]
1321pub struct ChannelList {
1422 pub selector: TextList,
1523 pub channel_display: ItemInfo,
1624 pub grid: Grid,
25 pub channels: Vec<FullChannelItem>,
1726}
1827
1928impl Default for ChannelList {
@@ -22,10 +31,11 @@ impl Default for ChannelList {
2231 selector: TextList::default(),
2332 channel_display: ItemInfo::default(),
2433 grid: Grid::new(
25 vec![Constraint::Percentage(40), Constraint::Percentage(60)],
34 vec![Constraint::Percentage(30), Constraint::Percentage(70)],
2635 vec![Constraint::Percentage(100)],
2736 )
2837 .unwrap(),
38 channels: Vec::new(),
2939 }
3040 }
3141}
@@ -53,6 +63,65 @@ impl ChannelList {
5363 .set_cursor_style(Style::default().fg(appearance.colors.outline));
5464 }
5565 }
66
67 fn select_at_cursor(&mut self, framework: &mut FrameworkClean) {
68 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
69
70 if self.selector.selected >= self.selector.items.len() {
71 self.selector.last().unwrap();
72 tasks.priority.push(Task::RenderAll);
73 }
74 }
75
76 fn update_unread(&mut self, subscriptions: &Subscriptions) {
77 self.selector
78 .set_items(
79 &[format!(
80 "All subscriptions{}",
81 if !subscriptions.0.is_empty()
82 && subscriptions.0.iter().any(|item| item.has_new)
83 {
84 "*"
85 } else {
86 ""
87 }
88 )]
89 .into_iter()
90 .chain(
91 subscriptions.0.iter().map(|subtiem| {
92 format!("{subtiem}{}", if subtiem.has_new { "*" } else { "" })
93 }),
94 )
95 .collect::<Vec<_>>(),
96 )
97 .unwrap();
98 }
99
100 fn set_env(&self, framework: &mut FrameworkClean) {
101 let id = if let Some(item) = &self.channel_display.item {
102 item.id().unwrap().to_string()
103 } else {
104 "invalid".to_string()
105 };
106 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
107 set_envs(
108 [
109 (
110 String::from("hover-channel-url"),
111 format!(
112 "{}channel/{id}",
113 match framework.data.global.get::<Status>().unwrap().provider {
114 Provider::YouTube => "https://youtube.com/",
115 Provider::Invidious => mainconfig.invidious_instance.as_str(),
116 }
117 ),
118 ),
119 (String::from("hover-channel-id"), id),
120 ]
121 .into_iter(),
122 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
123 )
124 }
56125}
57126
58127impl FrameworkItem for ChannelList {
@@ -62,24 +131,12 @@ impl FrameworkItem for ChannelList {
62131 _info: tui_additions::framework::ItemInfo,
63132 ) -> Result<(), Box<dyn std::error::Error>> {
64133 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
134 let subscriptions = framework.data.global.get::<Subscriptions>().unwrap();
65135 self.selector.set_border_type(appearance.borders);
66136 self.grid.set_border_type(appearance.borders);
137 self.channels = subscriptions.get_channels();
67138
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 )?;
139 self.update_unread(subscriptions);
83140
84141 if self.selector.selected >= self.selector.items.len() {
85142 self.selector.last()?;
@@ -107,6 +164,48 @@ impl FrameworkItem for ChannelList {
107164 frame.render_widget(self.grid.clone(), area);
108165 self.selector.set_height(chunks[1].height);
109166 frame.render_widget(self.selector.clone(), chunks[1]);
167
168 if self.selector.items.len() == 1 {
169 frame.render_widget(
170 Paragraph::new("Subscribe to some channels first, come back later\n\nHey, Siriusmart here. I originally planned to add a commands textlist at channel main pages so that you can subscribe to channels, but the complexity of this update is starting to get out of hand, as it requires the two items (channel and video list) to communicate with each other somehow. So for now the only ways you can subscribe to channels in single item page (videos or playlists), or run `youtube-tui help` to check out the related commands.\n\nThe rest will come in a few git commits.").wrap(tui::widgets::Wrap { trim: true }),
171 chunks[0],
172 );
173 return;
174 }
175 if self.selector.selected == 0 {
176 let now = chrono::Utc::now().timestamp() as u64;
177 let subscriptions = framework.data.global.get_mut::<Subscriptions>().unwrap();
178 let paragraph = subscriptions
179 .0
180 .iter()
181 .map(|item| {
182 format!(
183 " {} (last synced {} day{} ago){}",
184 item.channel.name,
185 (now - item.last_sync) / 86400,
186 if now - item.last_sync > 172800 {
187 "s"
188 } else {
189 ""
190 },
191 if item.has_new { "*" } else { "" }
192 )
193 })
194 .collect::<Vec<_>>()
195 .join("\n");
196 frame.render_widget(
197 Paragraph::new(format!("Subscriptions (last sync):\n\n{paragraph}")),
198 chunks[0],
199 );
200 return;
201 }
202 if self.channel_display.item.is_none() {
203 frame.render_widget(
204 Paragraph::new("Nothing to see here\n\nMaybe try something else"),
205 chunks[0],
206 );
207 return;
208 }
110209 self.channel_display
111210 .render(frame, framework, chunks[0], popup_render, info);
112211 }
@@ -124,20 +223,82 @@ impl FrameworkItem for ChannelList {
124223 KeyCode::Up if self.selector.up().is_ok() => tasks.priority.push(Task::RenderAll),
125224 KeyCode::Left if self.selector.first().is_ok() => tasks.priority.push(Task::RenderAll),
126225 KeyCode::Right if self.selector.last().is_ok() => tasks.priority.push(Task::RenderAll),
226 KeyCode::Enter => {
227 self.select_at_cursor(framework);
228 return Ok(());
229 }
127230 _ => return Ok(()),
128231 }
129232
130 if self.selector.selected == 0 {
131 if previously_selected != 0 {
233 if self.selector.selected != previously_selected {
234 framework
235 .data
236 .global
237 .get_mut::<Status>()
238 .unwrap()
239 .storage
240 .insert::<SubSelect>(SubSelect(self.selector.selected));
241
242 if self.selector.selected == 0 {
132243 self.channel_display.item = None;
133 tasks.priority.push(Task::ClearPage);
134244 framework
135245 .data
136 .global
137 .get_mut::<Status>()
246 .state
247 .get_mut::<Tasks>()
138248 .unwrap()
139 .render_image = true;
249 .priority
250 .push(Task::ClearPage);
251 } else {
252 if framework.data.state.get::<VidSelect>().unwrap().0 {
253 framework
254 .data
255 .state
256 .get_mut::<Tasks>()
257 .unwrap()
258 .priority
259 .push(Task::ClearPage);
260 }
261 self.channel_display.item = self
262 .channels
263 .get(self.selector.selected - 1)
264 .map(|channel| Item::FullChannel(channel.clone()));
265 let subscriptions = framework.data.global.get_mut::<Subscriptions>().unwrap();
266 let item = subscriptions.0.get_mut(self.selector.selected - 1);
267 let mut found = false;
268 match item {
269 Some(item)
270 if item.channel.id == self.channels[self.selector.selected - 1].id =>
271 {
272 if item.has_new {
273 item.has_new = false;
274 found = true;
275 }
276 }
277 _ => subscriptions.0.iter_mut().for_each(|item| {
278 if item.channel.id == self.channels[self.selector.selected - 1].id {
279 found = true;
280 item.has_new = false;
281 }
282 }),
283 }
284
285 if found {
286 self.update_unread(subscriptions);
287 }
288 self.set_env(framework);
140289 }
290
291 framework
292 .data
293 .global
294 .get_mut::<Status>()
295 .unwrap()
296 .render_image = true;
297
298 return Ok(());
299 }
300
301 if self.selector.selected == 0 {
141302 return Ok(());
142303 }
143304
@@ -154,14 +315,119 @@ impl FrameworkItem for ChannelList {
154315 != match &self.channel_display.item {
155316 Some(displayed) => displayed.id().unwrap_or_default(),
156317 None => "",
157 } =>
158 {
159 self.channel_display.item = Some(Item::FullChannel(item.channel.clone()))
160 }
318 } => {}
161319 Some(_) => {}
162320 None => self.channel_display.item = None,
163321 };
164322
165323 Ok(())
166324 }
325
326 fn mouse_event(
327 &mut self,
328 framework: &mut FrameworkClean,
329 x: u16,
330 y: u16,
331 _absolute_x: u16,
332 _absolute_y: u16,
333 ) -> bool {
334 let chunk = self
335 .grid
336 .chunks(
337 if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
338 {
339 prev_frame
340 } else {
341 return false;
342 },
343 )
344 .unwrap()[0][1];
345
346 if !chunk.intersects(Rect::new(x, y, 1, 1)) {
347 return false;
348 }
349
350 let previously_selected = self.selector.selected;
351 let y = (y - chunk.y) as usize + self.selector.scroll;
352
353 if y == self.selector.selected
354 || y == self.selector.selected + 2
355 || y == self.selector.selected + 1
356 {
357 self.select_at_cursor(framework);
358 return true;
359 }
360
361 // clicking on rows after the last item
362 if y > self.selector.items.len() + 1 {
363 return false;
364 }
365
366 // moving the cursor
367 if y <= self.selector.selected {
368 self.selector.selected = y;
369 }
370
371 if y >= self.selector.selected + 2 {
372 self.selector.selected = y - 2;
373 }
374
375 if self.selector.selected == previously_selected {
376 return false;
377 }
378
379 self.update(framework);
380 self.set_env(framework);
381 // render the new image
382 let status = framework.data.global.get_mut::<Status>().unwrap();
383 status.render_image = true;
384 status
385 .storage
386 .insert::<SubSelect>(SubSelect(self.selector.selected));
387
388 if framework.data.state.get::<VidSelect>().unwrap().0 {
389 framework
390 .data
391 .state
392 .get_mut::<Tasks>()
393 .unwrap()
394 .priority
395 .push(Task::ClearPage);
396 }
397 true
398 }
399}
400
401impl ChannelList {
402 // change `self.item` to the currently selected item
403 pub fn update(&mut self, framework: &mut FrameworkClean) {
404 if self.selector.selected == 0 || self.channels.get(self.selector.selected - 1).is_none() {
405 framework
406 .data
407 .global
408 .get_mut::<Status>()
409 .unwrap()
410 .render_image = true;
411 framework
412 .data
413 .state
414 .get_mut::<Tasks>()
415 .unwrap()
416 .priority
417 .push(Task::ClearPage);
418 self.channel_display.item = None;
419 return;
420 }
421
422 self.channel_display.item = Some(Item::FullChannel(
423 self.channels[self.selector.selected - 1].clone(),
424 ));
425 }
426}
427
428#[derive(Clone, Copy, Default)]
429pub struct SubSelect(pub usize);
430
431impl Key for SubSelect {
432 type Value = Self;
167433}
src/items/itemlist.rs +25 −8
@@ -336,18 +336,17 @@ impl FrameworkItem for ItemList {
336336 _ => unreachable!("item `ItemList` cannot be used in `{page:?}`"),
337337 }
338338
339 // update the items in text list
340 self.textlist.set_items(&self.items).unwrap();
341 self.update(framework);
342
339343 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
340344 let status = framework.data.global.get::<Status>().unwrap();
341
342345 if mainconfig.images.display() {
343346 // download thumbnails of all videos in the list
344347 download_all_images(self.items.iter().map(|item| item.into()).collect());
345348 }
346349
347 // update the items in text list
348 self.textlist.set_items(&self.items).unwrap();
349 self.update();
350
351350 set_envs(
352351 self.infalte_item_update(mainconfig, status).into_iter(),
353352 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
@@ -442,6 +441,7 @@ impl FrameworkItem for ItemList {
442441 return false;
443442 }
444443
444 let previously_selected = self.textlist.selected;
445445 let y = (y - chunk.y) as usize + self.textlist.scroll;
446446
447447 // clicking on already selected item
@@ -467,7 +467,11 @@ impl FrameworkItem for ItemList {
467467 self.textlist.selected = y - 2;
468468 }
469469
470 self.update();
470 if self.textlist.selected == previously_selected {
471 return false;
472 }
473
474 self.update(framework);
471475 set_envs(
472476 self.infalte_item_update(
473477 framework.data.global.get::<MainConfig>().unwrap(),
@@ -491,8 +495,21 @@ impl FrameworkItem for ItemList {
491495
492496impl ItemList {
493497 // change `self.item` to the currently selected item
494 pub fn update(&mut self) {
495 if self.items.is_empty() {
498 pub fn update(&mut self, framework: &mut FrameworkClean) {
499 if self.items.get(self.textlist.selected).is_none() {
500 framework
501 .data
502 .global
503 .get_mut::<Status>()
504 .unwrap()
505 .render_image = true;
506 framework
507 .data
508 .state
509 .get_mut::<Tasks>()
510 .unwrap()
511 .priority
512 .push(Task::ClearPage);
496513 self.info.item = None;
497514 return;
498515 }
src/items/mod.rs +2
@@ -17,3 +17,5 @@ mod channeldisplay;
1717pub use channeldisplay::*;
1818mod channellist;
1919pub use channellist::*;
20mod videolist;
21pub use videolist::*;
src/items/pagebutton.rs +3 −3
@@ -15,7 +15,7 @@ pub enum PageButton {
1515 ChannelVideos,
1616 ChannelPlaylists,
1717 History,
18 Subscriptions,
18 Feed,
1919 Library,
2020}
2121
@@ -37,7 +37,7 @@ impl PageButton {
3737 r#type: ChannelDisplayPageType::Playlists,
3838 }),
3939 Self::History => Page::MainMenu(MainMenuPage::History),
40 Self::Subscriptions => Page::Subscriptions(None),
40 Self::Feed => Page::Feed,
4141 Self::Library => Page::MainMenu(MainMenuPage::Library),
4242 }
4343 }
@@ -62,7 +62,7 @@ impl ToString for PageButton {
6262 Self::ChannelVideos => String::from("Videos"),
6363 Self::ChannelPlaylists => String::from("Playlists"),
6464 Self::History => String::from("History"),
65 Self::Subscriptions => String::from("Subscriptions"),
65 Self::Feed => String::from("Feed"),
6666 Self::Library => String::from("Library"),
6767 }
6868 }
src/items/searchbar.rs +2 −1
@@ -12,6 +12,7 @@ use tui::{
1212 widgets::{Block, Borders},
1313};
1414use tui_additions::{framework::FrameworkItem, widgets::TextField};
15use urlencoding::encode;
1516
1617/// the search bar item
1718#[derive(Clone, Default)]
@@ -137,7 +138,7 @@ impl FrameworkItem for SearchBar {
137138 }
138139
139140 let mut search = framework.data.state.get_mut::<Search>().unwrap();
140 search.query = self.text_field.content.clone();
141 search.query = encode(&self.text_field.content).into_owned();
141142 let search = search.clone();
142143 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
143144 tasks.priority.push(Task::LoadPage(Page::Search(search)));
src/items/videolist.rs added +513
@@ -0,0 +1,513 @@
1use crossterm::event::KeyCode;
2use tui::{
3 layout::{Constraint, Rect},
4 style::Style,
5};
6use tui_additions::{
7 framework::{FrameworkClean, FrameworkItem},
8 widgets::{Grid, TextList},
9};
10use typemap::Key;
11
12use crate::{
13 config::{AppearanceConfig, MainConfig, Provider},
14 global::{
15 functions::set_envs,
16 structs::{
17 ChannelDisplayPage, ChannelDisplayPageType, Item, MiniVideoItem, Page, StateEnvs,
18 Status, Subscriptions, Task, Tasks,
19 },
20 },
21};
22
23use super::{ItemInfo, SubSelect};
24
25#[derive(Clone)]
26pub struct VideoList {
27 pub items: Vec<MiniVideoItem>,
28 pub selector: TextList,
29 pub display: ItemInfo,
30 pub grid: Grid,
31 /// stores the latest known `self.selector.selected`
32 /// this allows for the item to "remember" its previous items after refreshes
33 /// if it is reset to 0 after refreshes, is can be displaying different stuff from channelist
34 pub previous: usize,
35 /// current channel id, is None if channellist is on `all feeds`
36 pub channel_id: Option<String>,
37}
38
39impl Default for VideoList {
40 fn default() -> Self {
41 Self {
42 selector: TextList::default(),
43 display: ItemInfo::default(),
44 items: Vec::new(),
45 grid: Grid::new(
46 vec![Constraint::Percentage(70), Constraint::Percentage(30)],
47 vec![Constraint::Percentage(100)],
48 )
49 .unwrap(),
50 previous: 0,
51 channel_id: None,
52 }
53 }
54}
55
56impl VideoList {
57 fn update_appearance(
58 &mut self,
59 info: &tui_additions::framework::ItemInfo,
60 appearance: &AppearanceConfig,
61 ) {
62 if info.selected {
63 self.grid
64 .set_border_style(Style::default().fg(appearance.colors.outline_selected));
65 self.selector
66 .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
67 } else if info.hover {
68 self.grid
69 .set_border_style(Style::default().fg(appearance.colors.outline_hover));
70 self.selector
71 .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
72 } else {
73 self.grid
74 .set_border_style(Style::default().fg(appearance.colors.outline));
75 self.selector
76 .set_cursor_style(Style::default().fg(appearance.colors.outline));
77 }
78 }
79
80 fn update_items(&mut self, subscriptions: &Subscriptions, subselect: usize) {
81 self.previous = subselect;
82 if subselect == 0 {
83 // if channellist is at index 0 (first item), then fetch all feeds
84 self.channel_id = None;
85 self.items = subscriptions.get_all_videos();
86 } else if subselect <= subscriptions.0.len() {
87 // or else, only fetch the one channel
88 self.channel_id = Some(subscriptions.0[subselect - 1].channel.id.clone());
89 self.items = subscriptions.0[subselect - 1].videos.clone();
90 } else {
91 // no idea when will this be true, just here to prevent some errors.
92 self.channel_id = None;
93 self.items.clear();
94 }
95 }
96
97 fn select_at_cursor(&self, framework: &mut FrameworkClean) {
98 // if "all feeds" is selected (channel_id is None)
99 // - Sync all
100 // - ...
101 //
102 // if "all feeds is not selected" (channel_id is Some(id))
103 // - Sync channel
104 // - View channel
105 // - Unsub
106 // - ...
107 match self.selector.selected {
108 // if "all feeds" and index is 0, sync all feeds
109 0 if self.channel_id.is_none() => framework
110 .data
111 .state
112 .get_mut::<Tasks>()
113 .unwrap()
114 .priority
115 .push(Task::Command("syncall".to_string())),
116 // if not "all feeds" and index is 0, sync only 1 feed
117 0 => framework
118 .data
119 .state
120 .get_mut::<Tasks>()
121 .unwrap()
122 .priority
123 .push(Task::Command(format!(
124 "sync {}",
125 self.channel_id.clone().unwrap()
126 ))),
127 // if view channel, load the channel page
128 1 if self.channel_id.is_some() => framework
129 .data
130 .state
131 .get_mut::<Tasks>()
132 .unwrap()
133 .priority
134 .push(Task::LoadPage(Page::ChannelDisplay(ChannelDisplayPage {
135 id: self.channel_id.clone().unwrap(),
136 r#type: ChannelDisplayPageType::Main,
137 }))),
138 // unsub
139 2 if self.channel_id.is_some() => framework
140 .data
141 .state
142 .get_mut::<Tasks>()
143 .unwrap()
144 .priority
145 .push(Task::Command(format!(
146 "unsub {} ;; reload",
147 self.channel_id.clone().unwrap()
148 ))),
149 // otherwise, load the video
150 i => framework
151 .data
152 .state
153 .get_mut::<Tasks>()
154 .unwrap()
155 .priority
156 .push(Task::LoadPage(Page::SingleItem(
157 crate::global::structs::SingleItemPage::Video(
158 self.items[i - if self.channel_id.is_some() { 3 } else { 1 }]
159 .id
160 .clone(),
161 ),
162 ))),
163 }
164 }
165
166 fn set_env(&self, framework: &mut FrameworkClean) {
167 // envs to set: hover-video-url and hover-video-id
168 let id = if let Some(item) = &self.display.item {
169 item.id().unwrap().to_string()
170 } else {
171 "invalid".to_string()
172 };
173 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
174 set_envs(
175 [
176 (
177 String::from("hover-video-url"),
178 format!(
179 "{}watch?v={id}",
180 match framework.data.global.get::<Status>().unwrap().provider {
181 Provider::YouTube => "https://youtube.com/",
182 Provider::Invidious => mainconfig.invidious_instance.as_str(),
183 }
184 ),
185 ),
186 (String::from("hover-video-id"), id),
187 ]
188 .into_iter(),
189 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
190 )
191 }
192}
193
194fn get_options(is_channel: bool) -> &'static [&'static str] {
195 // different predefined options to display depending on if "all feeds" is selected
196 if is_channel {
197 &["Sync feed", "View channel", "Remove subscription"]
198 } else {
199 &["Sync all feeds"]
200 }
201}
202
203impl FrameworkItem for VideoList {
204 fn load_item(
205 &mut self,
206 framework: &mut tui_additions::framework::FrameworkClean,
207 _info: tui_additions::framework::ItemInfo,
208 ) -> Result<(), Box<dyn std::error::Error>> {
209 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
210
211 self.grid.set_border_type(appearance.borders);
212 self.selector.set_border_type(appearance.borders);
213
214 // put the items into self.items
215 self.update_items(
216 framework.data.global.get::<Subscriptions>().unwrap(),
217 framework
218 .data
219 .global
220 .get::<Status>()
221 .unwrap()
222 .storage
223 .get::<SubSelect>()
224 .unwrap_or(&SubSelect(self.previous))
225 .0,
226 );
227 // update textlist to display the items in self.items
228 self.selector
229 .set_items(
230 &get_options(self.channel_id.is_some())
231 .iter()
232 .map(|s| s.to_string())
233 .chain(self.items.iter().map(|vid| vid.title.clone()))
234 .collect::<Vec<_>>(),
235 )
236 .unwrap();
237
238 // tell channellist whether an image is being displayed
239 // if yes, then the page is cleared if channellist cursor is moved
240 framework.data.state.insert::<VidSelect>(VidSelect(
241 self.selector.selected > if self.channel_id.is_some() { 2 } else { 0 },
242 ));
243 Ok(())
244 }
245
246 fn render(
247 &mut self,
248 frame: &mut tui::Frame<tui::backend::CrosstermBackend<std::io::Stdout>>,
249 framework: &mut tui_additions::framework::FrameworkClean,
250 area: tui::layout::Rect,
251 popup_render: bool,
252 info: tui_additions::framework::ItemInfo,
253 ) {
254 if popup_render {
255 return;
256 }
257
258 if let Some(subselect) = framework
259 .data
260 .global
261 .get::<Status>()
262 .unwrap()
263 .storage
264 .get::<SubSelect>()
265 {
266 self.update_items(
267 framework.data.global.get::<Subscriptions>().unwrap(),
268 subselect.0,
269 );
270 framework
271 .data
272 .state
273 .insert::<VidSelect>(VidSelect(self.selector.selected > 1));
274 self.selector
275 .set_items(
276 &get_options(self.channel_id.is_some())
277 .iter()
278 .map(|s| s.to_string())
279 .chain(self.items.iter().map(|vid| vid.title.clone()))
280 .collect::<Vec<_>>(),
281 )
282 .unwrap();
283 self.selector.scroll = 0;
284 self.selector.selected = 0;
285 self.set_env(framework);
286 }
287
288 let chunks = self.grid.chunks(area).unwrap()[0].clone();
289
290 self.update_appearance(
291 &info,
292 framework.data.global.get::<AppearanceConfig>().unwrap(),
293 );
294 frame.render_widget(self.grid.clone(), area);
295 if framework
296 .data
297 .global
298 .get::<Subscriptions>()
299 .unwrap()
300 .0
301 .is_empty()
302 {
303 return;
304 }
305
306 self.selector.set_height(chunks[1].height);
307 frame.render_widget(self.selector.clone(), chunks[0]);
308
309 if self.channel_id.is_some() {
310 match self.selector.selected {
311 0 => {}
312 1 => {}
313 2 => {}
314 _ => self
315 .display
316 .render(frame, framework, chunks[1], popup_render, info),
317 }
318 } else {
319 match self.selector.selected {
320 0 => {}
321 _ => self
322 .display
323 .render(frame, framework, chunks[1], popup_render, info),
324 }
325 }
326 }
327
328 fn key_event(
329 &mut self,
330 framework: &mut tui_additions::framework::FrameworkClean,
331 key: crossterm::event::KeyEvent,
332 _info: tui_additions::framework::ItemInfo,
333 ) -> Result<(), Box<dyn std::error::Error>> {
334 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
335 let previously_selected = self.selector.selected;
336 match key.code {
337 KeyCode::Down if self.selector.down().is_ok() => tasks.priority.push(Task::RenderAll),
338 KeyCode::Up if self.selector.up().is_ok() => tasks.priority.push(Task::RenderAll),
339 KeyCode::Left if self.selector.first().is_ok() => tasks.priority.push(Task::RenderAll),
340 KeyCode::Right if self.selector.last().is_ok() => tasks.priority.push(Task::RenderAll),
341 KeyCode::Enter => {
342 self.select_at_cursor(framework);
343 return Ok(());
344 }
345 _ => return Ok(()),
346 }
347
348 let offset = if self.channel_id.is_some() { 3 } else { 1 };
349 if self.selector.selected != previously_selected {
350 if self.selector.selected < offset {
351 self.display.item = None;
352 if previously_selected >= offset {
353 tasks.priority.push(Task::ClearPage);
354 }
355 } else {
356 self.display.item = self
357 .items
358 .get(self.selector.selected - offset)
359 .map(|item| Item::MiniVideo(item.clone()));
360 }
361 framework
362 .data
363 .state
364 .insert::<VidSelect>(VidSelect(self.selector.selected > 1));
365 framework
366 .data
367 .global
368 .get_mut::<Status>()
369 .unwrap()
370 .render_image = true;
371
372 self.set_env(framework);
373 return Ok(());
374 }
375
376 if self.selector.selected < offset {
377 return Ok(());
378 }
379
380 match framework
381 .data
382 .global
383 .get::<Subscriptions>()
384 .unwrap()
385 .0
386 .get(self.selector.selected - offset)
387 {
388 Some(item)
389 if item.channel.id
390 != match &self.display.item {
391 Some(displayed) => displayed.id().unwrap_or_default(),
392 None => "",
393 } => {}
394 Some(_) => {}
395 None => self.display.item = None,
396 };
397
398 Ok(())
399 }
400
401 fn mouse_event(
402 &mut self,
403 framework: &mut FrameworkClean,
404 x: u16,
405 y: u16,
406 _absolute_x: u16,
407 _absolute_y: u16,
408 ) -> bool {
409 let chunk = self
410 .grid
411 .chunks(
412 if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
413 {
414 prev_frame
415 } else {
416 return false;
417 },
418 )
419 .unwrap()[0][0];
420
421 if !chunk.intersects(Rect::new(x, y, 1, 1)) {
422 return false;
423 }
424
425 let previously_selected = self.selector.selected;
426 let y = (y - chunk.y) as usize + self.selector.scroll;
427
428 if y == self.selector.selected
429 || y == self.selector.selected + 2
430 || y == self.selector.selected + 1
431 {
432 self.select_at_cursor(framework);
433 return true;
434 }
435
436 // clicking on rows after the last item
437 if y > self.selector.items.len() + 1 {
438 return false;
439 }
440
441 // moving the cursor
442 if y <= self.selector.selected {
443 self.selector.selected = y;
444 }
445
446 if y >= self.selector.selected + 2 {
447 self.selector.selected = y - 2;
448 }
449
450 if self.selector.selected == previously_selected {
451 return false;
452 }
453
454 self.update(framework);
455 self.set_env(framework);
456 // render the new image
457 let status = framework.data.global.get_mut::<Status>().unwrap();
458 status.render_image = true;
459 status
460 .storage
461 .insert::<VidSelect>(VidSelect(self.selector.selected > 1));
462
463 if framework.data.state.get::<VidSelect>().unwrap().0 {
464 framework
465 .data
466 .state
467 .get_mut::<Tasks>()
468 .unwrap()
469 .priority
470 .push(Task::ClearPage);
471 }
472 true
473 }
474}
475
476// The below chunk of code is copied from channellist, which is copied from video list, i have no
477// idea what it does
478impl VideoList {
479 pub fn update(&mut self, framework: &mut FrameworkClean) {
480 let offset = if self.channel_id.is_some() { 3 } else { 1 };
481 if self.selector.selected < offset
482 || self.items.get(self.selector.selected - offset).is_none()
483 {
484 framework
485 .data
486 .global
487 .get_mut::<Status>()
488 .unwrap()
489 .render_image = true;
490 framework
491 .data
492 .state
493 .get_mut::<Tasks>()
494 .unwrap()
495 .priority
496 .push(Task::ClearPage);
497 self.display.item = None;
498 return;
499 }
500
501 self.display.item = Some(Item::MiniVideo(
502 self.items[self.selector.selected - offset].clone(),
503 ));
504 }
505}
506
507#[derive(Clone, Copy)]
508// if image is being displayed
509pub struct VidSelect(pub bool);
510
511impl Key for VidSelect {
512 type Value = Self;
513}
src/run.rs +8
@@ -23,6 +23,14 @@ pub fn run(
2323 continue;
2424 }
2525
26 framework
27 .data
28 .global
29 .get_mut::<Status>()
30 .unwrap()
31 .storage
32 .clear();
33
2634 // exits the function is `.exit` is true - a way for items/commands to exit the program
2735 if framework.data.global.get::<Status>().unwrap().exit {
2836 break;