Commit 896a63a991

896a63a991c369b3d7dce156b36e66f25371f918

parent: 6f8b64c4fa

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-06-05 17:56 UTC

channel support

Layout: unified · split

README.md +2 −4
@@ -1,10 +1,8 @@
11## Warning:
2* This app is incomplete but is basically usable
32* This app is only for *\*nix* systems
43
54## Changes made in this commit
6* Playlist support
7* Adaptive config files (e.g. auto update config files while preserving the original options)
5* Channel support
86
97## Installation
108Requirements: Git, Cargo and the Rust Compiler
@@ -138,9 +136,9 @@ The config files are located in `~/.config/youtube-tui`, run the program once to
138136> - "{video_save_location}"
139137> ```
140138## To Do
141* Channel support
142139* Update notice (e.g. when a new version is released on GitHub or crates.io, can be disabled in the config file)
143140* Keybind options (e.g. change the keybinds in the config file)
141* Channel search + item sorting
144142
145143## Bugs
146144* If there is a bug please open a GitHub issue thx :)
\ No newline at end of file
src/app/app.rs +23 −1
@@ -20,7 +20,7 @@ use tui::{
2020
2121use super::{
2222 config::Config,
23 pages::{item_info::ItemInfo, search::Search},
23 pages::{channel::Channel, item_info::ItemInfo, search::Search},
2424};
2525
2626#[derive(Debug)]
@@ -80,6 +80,7 @@ impl App {
8080 Item::MainMenu(item) => item.selectable(),
8181 Item::ItemInfo(item) => item.selectable(),
8282 Item::Search(item) => item.selectable(),
83 Item::Channel(item) => item.selectable(),
8384 } {
8485 row_vec.push((x, y));
8586 }
@@ -128,6 +129,14 @@ impl App {
128129 self.state[y].items[x].item = Item::Search(item);
129130 }
130131 }
132 Item::Channel(item) => {
133 let mut item = item.clone();
134 let hold = item.key_input(key, self);
135 self = hold.1;
136 if hold.0 {
137 self.state[y].items[x].item = Item::Channel(item);
138 }
139 }
131140 }
132141
133142 return self;
@@ -176,6 +185,13 @@ impl App {
176185 self.selected = Some((x, y));
177186 }
178187 }
188 Item::Channel(mut item) => {
189 let held = item.select(self);
190 self = held.0;
191 if held.1 {
192 self.selected = Some((x, y));
193 }
194 }
179195 }
180196
181197 return self;
@@ -260,6 +276,7 @@ impl App {
260276 Page::MainMenu(_) => MainMenu::min(),
261277 Page::ItemDisplay(_) => ItemInfo::min(),
262278 Page::Search => Search::min(),
279 Page::Channel(_, _) => Channel::min(),
263280 };
264281
265282 if size.width < min.0 || size.height < min.1 {
@@ -364,6 +381,11 @@ impl App {
364381 i.render_item(frame, chunk, selected, hover, self.popup_focus);
365382 false
366383 }
384
385 Item::Channel(i) => {
386 i.render_item(frame, chunk, selected, hover, self.popup_focus, &self.page);
387 false
388 }
367389 } {
368390 popups.push((item, selected, hover, chunk));
369391 }
src/app/config/commands.rs +5 −1
@@ -152,7 +152,11 @@ impl Default for CommandsConfig {
152152 playlist_shuffle_audio_all: CommandConfig {
153153 command: String::from("mpv"),
154154 open_in_console: true,
155 args: vec![String::from("--no-video"), String::from("{url}"), String::from("--shuffle")],
155 args: vec![
156 String::from("--no-video"),
157 String::from("{url}"),
158 String::from("--shuffle"),
159 ],
156160 },
157161 download_all_audio: CommandConfig {
158162 command: String::from("yt-dlp"),
src/app/config/main.rs +6 −2
@@ -1,4 +1,8 @@
1use std::{error::Error, fs::{self, OpenOptions}, io::Write};
1use std::{
2 error::Error,
3 fs::{self, OpenOptions},
4 io::Write,
5};
26
37use serde::{Deserialize, Serialize};
48
@@ -78,4 +82,4 @@ impl MainConfig {
7882
7983 Ok(main)
8084 }
81}
\ No newline at end of file
85}
src/app/pages/channel.rs added +441
@@ -0,0 +1,441 @@
1use std::{collections::LinkedList, error::Error};
2
3use crossterm::event::KeyCode;
4use tui::{
5 backend::Backend,
6 layout::{Alignment, Constraint, Rect},
7 style::{Color, Style},
8 widgets::{Block, BorderType, Borders, Paragraph},
9 Frame,
10};
11
12use crate::{
13 app::app::App,
14 functions::download_all_thumbnails,
15 structs::{FullChannel, Item, ListItem, MiniPlayList, MiniVideo, Page, Row, RowItem},
16 traits::{KeyInput, SelectItem},
17 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
18};
19
20use super::{
21 global::GlobalItem,
22 item_info::{DisplayItem, ItemInfo},
23};
24
25#[derive(Debug, Clone, Copy, PartialEq)]
26pub enum ChannelPage {
27 Home,
28 Playlists,
29 Videos,
30}
31
32#[derive(Debug, Clone)]
33pub enum ChannelItem {
34 InfoDisplay(ChannelDisplayItem),
35 SelectItems(ChannelPage),
36}
37
38#[derive(Debug, Clone)]
39pub enum ChannelDisplayItem {
40 Playlists(Vec<MiniPlayList>, TextList),
41 Videos(Vec<MiniVideo>, TextList),
42 Home(FullChannel),
43 Unknown,
44}
45
46impl ChannelItem {
47 pub fn load_item(&self, app: &App) -> Result<Self, Box<dyn Error>> {
48 let mut this = self.clone();
49
50 if let Page::Channel(channel_page, id) = &app.page {
51 if let ChannelItem::InfoDisplay(displayitem) = &mut this {
52 match channel_page {
53 ChannelPage::Home => {
54 let channel = app.client.channel(id, None)?;
55 let mut linked_list = LinkedList::new();
56 linked_list.push_back((
57 channel.authorThumbnails[4].url.clone(),
58 channel.authorId.clone(),
59 ));
60 let _ = download_all_thumbnails(linked_list);
61
62 *displayitem = ChannelDisplayItem::Home(channel.into());
63 }
64 ChannelPage::Playlists => {
65 let mut textlist = TextList::default();
66 let playlists = app
67 .client
68 .channel_playlists(id, None)?
69 .playlists
70 .into_iter()
71 .map(|item| {
72 textlist.items.push(item.title.clone());
73 item.into()
74 })
75 .collect::<Vec<MiniPlayList>>();
76
77 let mut linked_list = LinkedList::new();
78 for item in playlists.iter() {
79 if let Some(thumbnail) = &item.thumbnail {
80 linked_list
81 .push_back((thumbnail.clone(), item.playlist_id.clone()));
82 }
83 }
84 let _ = download_all_thumbnails(linked_list);
85
86 *displayitem = ChannelDisplayItem::Playlists(playlists, textlist);
87 }
88
89 ChannelPage::Videos => {
90 let mut textlist = TextList::default();
91 let videos = app
92 .client
93 .channel_videos(id, None)?
94 .videos
95 .into_iter()
96 .map(|item| {
97 textlist.items.push(item.title.clone());
98 item.into()
99 })
100 .collect::<Vec<MiniVideo>>();
101
102 let mut linked_list = LinkedList::new();
103 for item in videos.iter() {
104 linked_list
105 .push_back((item.video_thumbnail.clone(), item.video_id.clone()));
106 }
107 let _ = download_all_thumbnails(linked_list);
108
109 *displayitem = ChannelDisplayItem::Videos(videos, textlist);
110 }
111 }
112 }
113 }
114
115 Ok(this)
116 }
117
118 pub fn render_item<B: Backend>(
119 &mut self,
120 frame: &mut Frame<B>,
121 rect: Rect,
122 selected: bool,
123 hover: bool,
124 popup_focus: bool,
125 page: &Page,
126 ) {
127 let mut style = Style::default().fg(if selected {
128 Color::LightBlue
129 } else if hover {
130 Color::LightRed
131 } else {
132 Color::Reset
133 });
134
135 match self {
136 ChannelItem::InfoDisplay(displayitem) => match displayitem {
137 ChannelDisplayItem::Unknown => {
138 let block = Block::default()
139 .border_type(BorderType::Rounded)
140 .borders(Borders::ALL)
141 .border_style(style);
142
143 frame.render_widget(block, rect);
144 }
145 ChannelDisplayItem::Home(channel) => {
146 let block = Block::default()
147 .border_type(BorderType::Rounded)
148 .borders(Borders::ALL)
149 .border_style(style);
150
151 let inner = block.inner(rect);
152 frame.render_widget(block, rect);
153 frame.render_widget(
154 ItemDisplay {
155 item: ListItem::FullChannel(channel.clone()),
156 },
157 inner,
158 );
159 }
160 ChannelDisplayItem::Videos(videos, textlist) => {
161 let split = HorizontalSplit::default()
162 .percentages(vec![60, 40])
163 .border_style(Style::default().fg(if selected {
164 Color::LightBlue
165 } else if hover {
166 Color::LightRed
167 } else {
168 Color::Reset
169 }));
170
171 let chunks = split.inner(rect);
172
173 frame.render_widget(split, rect);
174
175 textlist.area(chunks[0]);
176 let mut textlist = textlist.clone();
177
178 if selected {
179 textlist.selected_style(Style::default().fg(Color::LightRed));
180 } else {
181 textlist.selected_style(Style::default().fg(Color::LightYellow));
182 }
183
184 if let Some(item) = videos.iter().nth(textlist.selected) {
185 if !popup_focus {
186 frame.render_widget(
187 ItemDisplay {
188 item: ListItem::MiniVideo(item.clone()),
189 },
190 chunks[1],
191 );
192 }
193 }
194
195 frame.render_widget(textlist, chunks[0]);
196 }
197 ChannelDisplayItem::Playlists(playlists, textlist) => {
198 let split = HorizontalSplit::default()
199 .percentages(vec![60, 40])
200 .border_style(Style::default().fg(if selected {
201 Color::LightBlue
202 } else if hover {
203 Color::LightRed
204 } else {
205 Color::Reset
206 }));
207
208 let chunks = split.inner(rect);
209
210 frame.render_widget(split, rect);
211
212 textlist.area(chunks[0]);
213 let mut textlist = textlist.clone();
214
215 if selected {
216 textlist.selected_style(Style::default().fg(Color::LightRed));
217 } else {
218 textlist.selected_style(Style::default().fg(Color::LightYellow));
219 }
220
221 if let Some(item) = playlists.iter().nth(textlist.selected) {
222 if !popup_focus {
223 frame.render_widget(
224 ItemDisplay {
225 item: ListItem::MiniPlayList(item.clone()),
226 },
227 chunks[1],
228 );
229 }
230 }
231
232 frame.render_widget(textlist, chunks[0]);
233 }
234 },
235 ChannelItem::SelectItems(selected_page) => {
236 if !hover {
237 if let Page::Channel(channel_page, _) = page {
238 if *selected_page == *channel_page {
239 style = style.fg(Color::LightYellow);
240 }
241 }
242 }
243
244 let block = Block::default()
245 .border_type(BorderType::Rounded)
246 .borders(Borders::ALL)
247 .border_style(style);
248 let paragraph = Paragraph::new(format!("{:?}", selected_page))
249 .block(block)
250 .alignment(Alignment::Center);
251
252 frame.render_widget(paragraph, rect);
253 }
254 }
255 }
256}
257
258impl KeyInput for ChannelItem {
259 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
260 match self {
261 ChannelItem::InfoDisplay(displayitem) => match displayitem {
262 ChannelDisplayItem::Videos(videos, textlist) => match key {
263 KeyCode::Up => {
264 textlist.up();
265 }
266 KeyCode::Down => {
267 textlist.down();
268 }
269 KeyCode::PageUp => {
270 textlist.selected = 0;
271 }
272 KeyCode::PageDown => {
273 textlist.selected = textlist.items.len() - 1;
274 }
275 KeyCode::Enter => {
276 let state = ItemInfo::default();
277 let mut history = app.history.clone();
278 history.push(app.into());
279
280 return (
281 false,
282 App {
283 history,
284 page: Page::ItemDisplay(DisplayItem::Video(
285 videos[textlist.selected].video_id.clone(),
286 )),
287 selectable: App::selectable(&state),
288 state,
289 ..Default::default()
290 },
291 );
292 }
293 _ => {}
294 },
295
296 ChannelDisplayItem::Playlists(playlists, textlist) => match key {
297 KeyCode::Up => {
298 textlist.up();
299 }
300 KeyCode::Down => {
301 textlist.down();
302 }
303 KeyCode::PageUp => {
304 textlist.selected = 0;
305 }
306 KeyCode::PageDown => {
307 textlist.selected = textlist.items.len() - 1;
308 }
309 KeyCode::Enter => {
310 let state = ItemInfo::default();
311 let mut history = app.history.clone();
312 history.push(app.into());
313
314 return (
315 false,
316 App {
317 history,
318 page: Page::ItemDisplay(DisplayItem::PlayList(
319 playlists[textlist.selected].playlist_id.clone(),
320 )),
321 selectable: App::selectable(&state),
322 state,
323 ..Default::default()
324 },
325 );
326 }
327 _ => {}
328 },
329
330 _ => unreachable!(),
331 },
332 _ => {
333 unreachable!()
334 }
335 }
336
337 (true, app)
338 }
339}
340
341impl SelectItem for ChannelItem {
342 fn select(&mut self, app: App) -> (App, bool) {
343 let cloned = self.clone();
344 match &cloned {
345 ChannelItem::InfoDisplay(_) => (app, true),
346 ChannelItem::SelectItems(tab) => {
347 if let Page::Channel(channel_page, id) = &app.page.clone() {
348 if *tab == *channel_page {
349 return (app, false);
350 }
351
352 let state = Channel::default();
353 let mut history = app.history.clone();
354 history.push(app.into());
355
356 return (
357 App {
358 history,
359 page: Page::Channel(tab.clone(), id.clone()),
360 selectable: App::selectable(&state),
361 state,
362 ..Default::default()
363 },
364 false,
365 );
366 } else {
367 (app, false)
368 }
369 }
370 }
371 }
372
373 fn selectable(&self) -> bool {
374 true
375 }
376}
377
378pub struct Channel;
379
380impl Channel {
381 pub fn message() -> String {
382 String::from("Loading channel info...")
383 }
384
385 pub fn min() -> (u16, u16) {
386 (45, 15)
387 }
388
389 pub fn default() -> Vec<Row> {
390 vec![
391 Row {
392 items: vec![
393 RowItem {
394 item: Item::Global(GlobalItem::SearchBar),
395 constraint: Constraint::Min(16),
396 },
397 RowItem {
398 item: Item::Global(GlobalItem::SearchSettings),
399 constraint: Constraint::Length(5),
400 },
401 ],
402 centered: false,
403 height: Constraint::Length(3),
404 },
405 Row {
406 items: vec![
407 RowItem {
408 item: Item::Channel(ChannelItem::SelectItems(ChannelPage::Home)),
409 constraint: Constraint::Length(15),
410 },
411 RowItem {
412 item: Item::Channel(ChannelItem::SelectItems(ChannelPage::Videos)),
413 constraint: Constraint::Length(15),
414 },
415 RowItem {
416 item: Item::Channel(ChannelItem::SelectItems(ChannelPage::Playlists)),
417 constraint: Constraint::Length(15),
418 },
419 ],
420 centered: true,
421 height: Constraint::Length(3),
422 },
423 Row {
424 items: vec![RowItem {
425 item: Item::Channel(ChannelItem::InfoDisplay(ChannelDisplayItem::Unknown)),
426 constraint: Constraint::Percentage(100),
427 }],
428 centered: false,
429 height: Constraint::Min(6),
430 },
431 Row {
432 items: vec![RowItem {
433 item: Item::Global(GlobalItem::MessageBar),
434 constraint: Constraint::Percentage(100),
435 }],
436 centered: false,
437 height: Constraint::Length(3),
438 },
439 ]
440 }
441}
src/app/pages/item_info.rs +41 −9
@@ -21,7 +21,10 @@ use tui::{
2121 Frame,
2222};
2323
24use super::global::GlobalItem;
24use super::{
25 channel::{Channel, ChannelPage},
26 global::GlobalItem,
27};
2528
2629#[derive(Debug, Clone)]
2730pub enum ItemInfoItem {
@@ -242,9 +245,23 @@ impl KeyInput for ItemInfoItem {
242245 run_command(command, app.message.clone());
243246 }
244247 5 => {
245 *app.message.lock().unwrap() = Some(String::from(
246 "Too lazy to implement that what do you expect?",
247 ));
248 let state = Channel::default();
249 let mut history = app.history.clone();
250 history.push(app.into());
251
252 return (
253 false,
254 App {
255 history,
256 page: Page::Channel(
257 ChannelPage::Home,
258 videoinfo.video.channel_id.clone(),
259 ),
260 selectable: App::selectable(&state),
261 state,
262 ..Default::default()
263 },
264 );
248265 }
249266 6 => {
250267 videoinfo.mode.toggle();
@@ -499,9 +516,24 @@ impl KeyInput for ItemInfoItem {
499516 }
500517
501518 7 => {
502 *app.message.lock().unwrap() = Some(String::from(
503 "Too lazy to implement that what do you expect?",
504 ));
519 let state = Channel::default();
520 let mut history = app.history.clone();
521 history.push(app.into());
522
523 return (
524 false,
525 App {
526 history,
527 page: Page::Channel(
528 ChannelPage::Home,
529 playlistinfo.playlist.author_id.clone(),
530 ),
531 selectable: App::selectable(&state),
532 state,
533 load: true,
534 ..Default::default()
535 },
536 );
505537 }
506538
507539 8 => {
@@ -562,7 +594,7 @@ impl ItemInfoItem {
562594 &self,
563595 app: &App,
564596 watch_history: &mut WatchHistory,
565 ) -> Result<Box<Self>, Box<dyn Error>> {
597 ) -> Result<Self, Box<dyn Error>> {
566598 let mut this = self.clone();
567599
568600 if let ItemInfoItem::Unknown = this {
@@ -650,7 +682,7 @@ impl ItemInfoItem {
650682 _ => {}
651683 }
652684 }
653 Ok(Box::new(this))
685 Ok(this)
654686 }
655687
656688 pub fn render_item<B: Backend>(
src/app/pages/main_menu.rs +6 −14
@@ -69,24 +69,16 @@ impl KeyInput for MainMenuItem {
6969 page: Page::ItemDisplay(
7070 match list.iter().nth(textlist.selected).unwrap() {
7171 ListItem::FullVideo(item) => {
72 DisplayItem::Video(
73 item.video_id.clone(),
74 )
72 DisplayItem::Video(item.video_id.clone())
7573 }
7674 ListItem::FullPlayList(item) => {
77 DisplayItem::PlayList(
78 item.playlist_id.clone(),
79 )
75 DisplayItem::PlayList(item.playlist_id.clone())
8076 }
8177 ListItem::MiniPlayList(item) => {
82 DisplayItem::PlayList(
83 item.playlist_id.clone(),
84 )
78 DisplayItem::PlayList(item.playlist_id.clone())
8579 }
8680 ListItem::MiniVideo(item) => {
87 DisplayItem::Video(
88 item.video_id.clone(),
89 )
81 DisplayItem::Video(item.video_id.clone())
9082 }
9183 _ => unreachable!(),
9284 },
@@ -107,7 +99,7 @@ impl KeyInput for MainMenuItem {
10799}
108100
109101impl MainMenuItem {
110 pub fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn Error>> {
102 pub fn load_item(&self, app: &App) -> Result<Self, Box<dyn Error>> {
111103 let mut this = self.clone();
112104
113105 match &mut this {
@@ -209,7 +201,7 @@ impl MainMenuItem {
209201 _ => {}
210202 }
211203
212 Ok(Box::new(this))
204 Ok(this)
213205 }
214206
215207 pub fn render_item<B: Backend>(
src/app/pages/mod.rs +2 −1
@@ -1,4 +1,5 @@
1pub mod channel;
12pub mod global;
23pub mod item_info;
34pub mod main_menu;
4pub mod search;
\ No newline at end of file
5pub mod search;
src/app/pages/search.rs +46 −3
@@ -12,12 +12,13 @@ use tui::{
1212use crate::{
1313 app::app::App,
1414 functions::download_all_thumbnails,
15 structs::{Item, ListItem, MiniPlayList, MiniVideo, Page, Row, RowItem},
15 structs::{Item, ListItem, MiniChannel, MiniPlayList, MiniVideo, Page, Row, RowItem},
1616 traits::{KeyInput, SelectItem},
1717 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
1818};
1919
2020use super::{
21 channel::{Channel, ChannelPage},
2122 global::GlobalItem,
2223 item_info::{DisplayItem, ItemInfo},
2324 main_menu::textlist_from_video_list,
@@ -123,6 +124,26 @@ impl KeyInput for SearchItem {
123124 );
124125 }
125126
127 ListItem::MiniChannel(channel) => {
128 let state = Channel::default();
129 let mut history = app.history.clone();
130 history.push(app.into());
131
132 return (
133 false,
134 App {
135 history,
136 page: Page::Channel(
137 ChannelPage::Home,
138 channel.author_id.clone(),
139 ),
140 selectable: App::selectable(&state),
141 state,
142 ..Default::default()
143 },
144 );
145 }
146
126147 _ => {}
127148 }
128149 }
@@ -136,7 +157,7 @@ impl KeyInput for SearchItem {
136157}
137158
138159impl SearchItem {
139 pub fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn Error>> {
160 pub fn load_item(&self, app: &App) -> Result<Self, Box<dyn Error>> {
140161 let mut this = self.clone();
141162
142163 match &mut this {
@@ -191,6 +212,19 @@ impl SearchItem {
191212 items.push_back(ListItem::MiniPlayList(MiniPlayList::from(item)));
192213 }
193214
215 InvidiousSearchItem::Channel {
216 author: _,
217 authorId: _,
218 authorUrl: _,
219 authorThumbnails: _,
220 subCount: _,
221 videoCount: _,
222 description: _,
223 descriptionHtml: _,
224 } => {
225 items.push_back(ListItem::MiniChannel(MiniChannel::from(item)));
226 }
227
194228 _ => {}
195229 }
196230 }
@@ -226,6 +260,15 @@ impl SearchItem {
226260 }
227261 }
228262
263 ListItem::MiniChannel(channel) => {
264 thumbnails.push_back((
265 format!("https:{}", channel.thumbnail.clone()),
266 channel.author_id.clone(),
267 ));
268
269 // panic!("{:?}", channel.thumbnail.clone());
270 }
271
229272 _ => {}
230273 }
231274 }
@@ -236,7 +279,7 @@ impl SearchItem {
236279 }
237280 }
238281
239 Ok(Box::new(this))
282 Ok(this)
240283 }
241284
242285 pub fn render_item<B: Backend>(
src/functions/download_all_thumbnails.rs +1 −4
@@ -20,9 +20,7 @@ pub fn download_all_thumbnails(
2020 Ok(())
2121}
2222
23pub async fn download_items(
24 urls: LinkedList<(String, String)>,
25) -> Result<(), Box<dyn Error>> {
23pub async fn download_items(urls: LinkedList<(String, String)>) -> Result<(), Box<dyn Error>> {
2624 let mut actions = Vec::new();
2725 let mut path = home::home_dir().expect("Cannot get your home directory");
2826 path.push(".cache");
@@ -30,7 +28,6 @@ pub async fn download_items(
3028 path.push("thumbnails");
3129
3230 for (url, video_id) in urls.iter() {
33
3431 path.push(format!("{}.png", video_id));
3532
3633 if !path.exists() {
src/functions/mod.rs +1 −1
@@ -5,4 +5,4 @@ mod insert_vec;
55pub use insert_vec::*;
66
77mod center_rect;
8pub use center_rect::*;
\ No newline at end of file
8pub use center_rect::*;
src/main.rs +20 −4
@@ -11,7 +11,7 @@ use tui::{
1111use youtube_tui::{
1212 app::{
1313 app::App,
14 pages::{item_info::ItemInfo, main_menu::MainMenu, search::Search},
14 pages::{channel::Channel, item_info::ItemInfo, main_menu::MainMenu, search::Search},
1515 },
1616 structs::{Item, Page, Row, RowItem},
1717};
@@ -53,6 +53,7 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
5353 Page::MainMenu(_) => MainMenu::message(),
5454 Page::ItemDisplay(_) => ItemInfo::message(),
5555 Page::Search => Search::message(),
56 Page::Channel(_, _) => Channel::message(),
5657 });
5758 terminal.clear()?;
5859 ui(&mut terminal, &mut app)?;
@@ -64,7 +65,7 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
6465 Item::MainMenu(item) => match item.load_item(&app) {
6566 Ok(new) => {
6667 row_vec.push(RowItem {
67 item: Item::MainMenu(*new),
68 item: Item::MainMenu(new),
6869 ..*row_item
6970 });
7071 }
@@ -81,7 +82,7 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
8182 match item.load_item(&app, &mut watch_history) {
8283 Ok(new) => {
8384 row_vec.push(RowItem {
84 item: Item::ItemInfo(*new),
85 item: Item::ItemInfo(new),
8586 ..*row_item
8687 });
8788 }
@@ -98,7 +99,7 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
9899 Item::Search(item) => match item.load_item(&app) {
99100 Ok(new) => {
100101 row_vec.push(RowItem {
101 item: Item::Search(*new),
102 item: Item::Search(new),
102103 ..*row_item
103104 });
104105 }
@@ -110,6 +111,21 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
110111 *app.message.lock().unwrap() = Some(e.to_string());
111112 }
112113 },
114 Item::Channel(item) => match item.load_item(&app) {
115 Ok(new) => {
116 row_vec.push(RowItem {
117 item: Item::Channel(new),
118 ..*row_item
119 });
120 }
121 Err(e) => {
122 row_vec.push(RowItem {
123 item: Item::Channel(item.clone()),
124 ..*row_item
125 });
126 *app.message.lock().unwrap() = Some(e.to_string());
127 }
128 },
113129 _ => {
114130 row_vec.push(RowItem {
115131 item: row_item.item.clone(),
src/structs/fullchannel.rs added +28
@@ -0,0 +1,28 @@
1use invidious::structs::channel::Channel;
2use serde::{Deserialize, Serialize};
3use thousands::Separable;
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct FullChannel {
7 pub author: String,
8 pub author_id: String,
9 pub author_url: String,
10 pub thumbnail: String,
11 pub description: String,
12 pub sub_count: String,
13 pub total_views: String,
14}
15
16impl From<Channel> for FullChannel {
17 fn from(original: Channel) -> Self {
18 Self {
19 author: original.author,
20 author_id: original.authorId,
21 author_url: original.authorUrl,
22 thumbnail: original.authorThumbnails[4].url.clone(),
23 description: original.description,
24 sub_count: original.subCount.separate_with_commas(),
25 total_views: original.totalViews.separate_with_commas(),
26 }
27 }
28}
src/structs/fullvideo.rs +1 −1
@@ -1,7 +1,7 @@
11use chrono::{DateTime, NaiveDateTime, Utc};
22use invidious::structs::video::Video;
3use thousands::Separable;
43use serde::{Deserialize, Serialize};
4use thousands::Separable;
55
66#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct FullVideo {
src/structs/listitem.rs +15 −1
@@ -1,7 +1,7 @@
11use crate::structs::{FullVideo, MiniVideo};
22use serde::{Deserialize, Serialize};
33
4use super::{FullPlayList, MiniPlayList};
4use super::{FullChannel, FullPlayList, MiniChannel, MiniPlayList};
55
66#[derive(Debug, Clone, Deserialize, Serialize)]
77pub enum ListItem {
@@ -9,6 +9,8 @@ pub enum ListItem {
99 FullVideo(FullVideo),
1010 MiniPlayList(MiniPlayList),
1111 FullPlayList(FullPlayList),
12 MiniChannel(MiniChannel),
13 FullChannel(FullChannel),
1214 PageTurner(bool), // true: +1 | false: -1
1315}
1416
@@ -58,6 +60,18 @@ impl ListItem {
5860 .into_iter()
5961 .filter(|c| !c.is_ascii_control())
6062 .collect(),
63 ListItem::MiniChannel(channel) => channel
64 .author
65 .chars()
66 .into_iter()
67 .filter(|c| !c.is_ascii_control())
68 .collect(),
69 ListItem::FullChannel(channel) => channel
70 .author
71 .chars()
72 .into_iter()
73 .filter(|c| !c.is_ascii_control())
74 .collect(),
6175 ListItem::PageTurner(turner) => {
6276 if *turner {
6377 String::from("Next Page")
src/structs/minichannel.rs added +41
@@ -0,0 +1,41 @@
1use invidious::structs::hidden::SearchItem;
2use serde::{Deserialize, Serialize};
3use thousands::Separable;
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct MiniChannel {
7 pub author: String,
8 pub author_url: String,
9 pub author_id: String,
10 pub thumbnail: String,
11 pub description: String,
12 pub sub_count: String,
13 pub video_count: String,
14}
15
16impl From<SearchItem> for MiniChannel {
17 fn from(original: SearchItem) -> Self {
18 match original {
19 SearchItem::Channel {
20 author,
21 authorId,
22 authorUrl,
23 authorThumbnails,
24 subCount,
25 videoCount,
26 description,
27 descriptionHtml: _,
28 } => Self {
29 author,
30 author_id: authorId,
31 author_url: authorUrl,
32 thumbnail: authorThumbnails[4].url.clone(),
33 description,
34 sub_count: subCount.separate_with_commas(),
35 video_count: videoCount.to_string(),
36 },
37
38 _ => unreachable!(),
39 }
40 }
41}
src/structs/miniplaylist.rs +19 −1
@@ -1,4 +1,4 @@
1use invidious::structs::hidden::SearchItem;
1use invidious::structs::hidden::{Playlist, SearchItem};
22use serde::{Deserialize, Serialize};
33
44#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -43,3 +43,21 @@ impl From<SearchItem> for MiniPlayList {
4343 }
4444 }
4545}
46
47impl From<Playlist> for MiniPlayList {
48 fn from(original: Playlist) -> Self {
49 Self {
50 title: original.title,
51 playlist_id: original.playlistId,
52 author: original.author,
53 author_id: original.authorId,
54 author_url: original.authorUrl,
55 video_count: original.videoCount as usize,
56 thumbnail: if original.videos.len() == 0 {
57 None
58 } else {
59 Some(original.videos[0].videoThumbnails[4].url.clone())
60 },
61 }
62 }
63}
src/structs/minivideo.rs +71 −28
@@ -1,7 +1,9 @@
11use chrono::{prelude::*, Utc};
2use invidious::structs::hidden::{PopularItem, TrendingVideo, SearchItem, PlaylistItem};
3use thousands::Separable;
2use invidious::structs::hidden::{
3 ChannelVideo, PlaylistItem, PopularItem, SearchItem, TrendingVideo,
4};
45use serde::{Deserialize, Serialize};
6use thousands::Separable;
57
68#[derive(Debug, Clone, Serialize, Deserialize)]
79pub struct MiniVideo {
@@ -75,31 +77,45 @@ impl From<PopularItem> for MiniVideo {
7577impl From<SearchItem> for MiniVideo {
7678 fn from(original: SearchItem) -> Self {
7779 match original {
78 SearchItem::Video { title, videoId, author, authorId: _, authorUrl, lengthSeconds, videoThumbnails, description, descriptionHtml: _, viewCount, published, publishedText, liveNow: _, paid: _, premium: _ } => {
79 MiniVideo {
80 title: title,
81 video_id: videoId,
82 video_thumbnail: videoThumbnails[0].url.clone(),
83 length: hrtime::from_sec_padded(lengthSeconds as u64),
84 view_count: Some(viewCount.separate_with_commas()),
85 author: author,
86 author_url: authorUrl,
87 published: Some(format!(
88 "{}{}",
89 publishedText,
90 if Utc::now().timestamp() - published as i64 > 86400 {
91 let datetime: DateTime<Utc> = DateTime::from_utc(
92 NaiveDateTime::from_timestamp(published as i64, 0),
93 Utc,
94 );
95 format!(" [{}]", datetime.format("%Y/%m/%d"))
96 } else {
97 String::new()
98 }
99 )),
100 description: Some(description),
101 }
102 }
80 SearchItem::Video {
81 title,
82 videoId,
83 author,
84 authorId: _,
85 authorUrl,
86 lengthSeconds,
87 videoThumbnails,
88 description,
89 descriptionHtml: _,
90 viewCount,
91 published,
92 publishedText,
93 liveNow: _,
94 paid: _,
95 premium: _,
96 } => MiniVideo {
97 title: title,
98 video_id: videoId,
99 video_thumbnail: videoThumbnails[0].url.clone(),
100 length: hrtime::from_sec_padded(lengthSeconds as u64),
101 view_count: Some(viewCount.separate_with_commas()),
102 author: author,
103 author_url: authorUrl,
104 published: Some(format!(
105 "{}{}",
106 publishedText,
107 if Utc::now().timestamp() - published as i64 > 86400 {
108 let datetime: DateTime<Utc> = DateTime::from_utc(
109 NaiveDateTime::from_timestamp(published as i64, 0),
110 Utc,
111 );
112 format!(" [{}]", datetime.format("%Y/%m/%d"))
113 } else {
114 String::new()
115 }
116 )),
117 description: Some(description),
118 },
103119
104120 _ => unreachable!(),
105121 }
@@ -118,7 +134,34 @@ impl From<PlaylistItem> for MiniVideo {
118134 author_url: original.authorUrl,
119135 published: None,
120136 description: None,
137 }
138 }
139}
121140
141impl From<ChannelVideo> for MiniVideo {
142 fn from(original: ChannelVideo) -> Self {
143 MiniVideo {
144 title: original.title,
145 video_id: original.videoId,
146 video_thumbnail: original.videoThumbnails[4].url.clone(),
147 length: hrtime::from_sec_padded(original.lengthSeconds as u64),
148 view_count: Some(original.viewCount.separate_with_commas()),
149 author: original.author,
150 author_url: original.authorUrl,
151 published: Some(format!(
152 "{}{}",
153 original.publishedText,
154 if Utc::now().timestamp() - original.published as i64 > 86400 {
155 let datetime: DateTime<Utc> = DateTime::from_utc(
156 NaiveDateTime::from_timestamp(original.published as i64, 0),
157 Utc,
158 );
159 format!(" [{}]", datetime.format("%Y/%m/%d"))
160 } else {
161 String::new()
162 }
163 )),
164 description: None,
122165 }
123166 }
124}
\ No newline at end of file
167}
src/structs/mod.rs +7 −1
@@ -26,4 +26,10 @@ mod miniplaylist;
2626pub use miniplaylist::*;
2727
2828mod fullplaylist;
29pub use fullplaylist::*;
\ No newline at end of file
29pub use fullplaylist::*;
30
31mod minichannel;
32pub use minichannel::*;
33
34mod fullchannel;
35pub use fullchannel::*;
src/structs/page.rs +4 −1
@@ -1,9 +1,12 @@
1use crate::app::pages::{item_info::DisplayItem, main_menu::MainMenuSelector};
1use crate::app::pages::{
2 channel::ChannelPage, item_info::DisplayItem, main_menu::MainMenuSelector,
3};
24
35#[derive(Debug, PartialEq, Clone)]
46pub enum Page {
57 MainMenu(MainMenuSelector),
68 ItemDisplay(DisplayItem),
9 Channel(ChannelPage, String),
710 Search,
811}
912
src/structs/states.rs +5 −1
@@ -1,6 +1,9 @@
11use tui::layout::Constraint;
22
3use crate::app::pages::{global::GlobalItem, item_info::ItemInfoItem, main_menu::MainMenuItem, search::SearchItem};
3use crate::app::pages::{
4 channel::ChannelItem, global::GlobalItem, item_info::ItemInfoItem, main_menu::MainMenuItem,
5 search::SearchItem,
6};
47
58#[derive(Debug, Clone)]
69pub enum Item {
@@ -8,6 +11,7 @@ pub enum Item {
811 MainMenu(MainMenuItem),
912 ItemInfo(ItemInfoItem),
1013 Search(SearchItem),
14 Channel(ChannelItem),
1115}
1216
1317#[derive(Debug, Clone)]
src/traits/mod.rs +1 −1
@@ -2,4 +2,4 @@ mod select_item;
22pub use select_item::*;
33
44mod key_input;
5pub use key_input::*;
\ No newline at end of file
5pub use key_input::*;
src/widgets/force_clear.rs +9 −2
@@ -1,4 +1,9 @@
1use tui::{widgets::Widget, buffer::Buffer, layout::Rect, style::{Color, Style}};
1use tui::{
2 buffer::Buffer,
3 layout::Rect,
4 style::{Color, Style},
5 widgets::Widget,
6};
27
38pub struct ForceClear;
49
@@ -6,7 +11,9 @@ impl Widget for ForceClear {
611 fn render(self, rect: Rect, buffer: &mut Buffer) {
712 for y in rect.y..rect.y + rect.height {
813 for x in rect.x..rect.x + rect.width {
9 buffer.get_mut(x, y).set_style(Style::default().bg(Color::DarkGray));
14 buffer
15 .get_mut(x, y)
16 .set_style(Style::default().bg(Color::DarkGray));
1017 }
1118 }
1219 }
src/widgets/item_display.rs +160 −2
@@ -16,6 +16,165 @@ pub struct ItemDisplay {
1616impl Widget for ItemDisplay {
1717 fn render(self, area: Rect, buf: &mut Buffer) {
1818 match self.item {
19 ListItem::MiniChannel(channel) => {
20 let mut path = home::home_dir().expect("Cannot get your home directory");
21 path.push(".cache");
22 path.push("youtube-tui");
23 path.push("thumbnails");
24 path.push(format!("{}.png", channel.author_id));
25
26 let exists = path.exists();
27 let mut image_transform = area;
28 if exists {
29 if image_transform.width * 2 > image_transform.height {
30 image_transform.width = image_transform.height / 2;
31 }
32 image_transform.height = image_transform.width / 2;
33 // image_transform.width = image_transform.height * 2;
34
35 let conf = Config {
36 width: Some(image_transform.width as u32),
37 height: Some(image_transform.height as u32),
38 x: image_transform.x,
39 y: image_transform.y as i16,
40 ..Default::default()
41 };
42
43 let _ = print_from_file(path.as_os_str(), &conf);
44 }
45
46 let mut y = if exists {
47 image_transform.y + image_transform.height
48 } else {
49 area.y
50 };
51
52 let mut to_print = Vec::new();
53 to_print.push((String::from("[Channel]"), Style::default().fg(Color::Gray)));
54 to_print.push((channel.author, Style::default().fg(Color::LightBlue)));
55 to_print.push((
56 format!("Subscribers: {}", channel.sub_count),
57 Style::default().fg(Color::LightYellow),
58 ));
59 to_print.push((
60 format!("Video Count: {}", channel.video_count),
61 Style::default().fg(Color::LightCyan),
62 ));
63
64 to_print.push((
65 String::from("Description: "),
66 Style::default().fg(Color::Gray),
67 ));
68
69 for (mut item, style) in to_print {
70 if y > area.height + area.y - 1 {
71 return;
72 }
73
74 if item.len() > area.width as usize {
75 item = format!("{}...", &item[..area.width as usize - 3]);
76 }
77 buf.set_string(area.x, y, item, style);
78 y += 1;
79 }
80
81 if y < area.height + area.y {
82 let rect = Rect {
83 x: area.x,
84 y: y,
85 width: area.width,
86 height: area.height + area.y - y,
87 };
88
89 let paragraph = Paragraph::new(channel.description.clone())
90 .wrap(Wrap { trim: true })
91 .alignment(Alignment::Left)
92 .style(Style::default().fg(Color::Gray));
93
94 paragraph.render(rect, buf);
95 }
96 }
97 ListItem::FullChannel(channel) => {
98 let mut path = home::home_dir().expect("Cannot get your home directory");
99 path.push(".cache");
100 path.push("youtube-tui");
101 path.push("thumbnails");
102 path.push(format!("{}.png", channel.author_id));
103
104 let exists = path.exists();
105 let mut image_transform = area;
106 if exists {
107 image_transform.height = image_transform.width * 9 / 64;
108 image_transform.width = image_transform.height * 2;
109
110 let conf = Config {
111 width: Some(image_transform.width as u32),
112 height: Some(image_transform.height as u32),
113 x: image_transform.x,
114 y: image_transform.y as i16,
115 ..Default::default()
116 };
117
118 let _ = print_from_file(path.as_os_str(), &conf);
119 }
120
121 let mut y = if exists {
122 image_transform.y + image_transform.height
123 } else {
124 area.y
125 };
126
127 let mut to_print = Vec::new();
128 to_print.push((String::from("[Channel]"), Style::default().fg(Color::Gray)));
129 to_print.push((channel.author, Style::default().fg(Color::LightBlue)));
130 to_print.push((
131 format!("Subscribers: {}", channel.sub_count),
132 Style::default().fg(Color::LightYellow),
133 ));
134
135 to_print.push((
136 String::from("Description: "),
137 Style::default().fg(Color::Gray),
138 ));
139
140 to_print.push((
141 format!("Total Views: {}", channel.total_views),
142 Style::default().fg(Color::LightCyan),
143 ));
144
145 to_print.push((
146 String::from("Description: "),
147 Style::default().fg(Color::Gray),
148 ));
149
150 for (mut item, style) in to_print {
151 if y > area.height + area.y - 1 {
152 return;
153 }
154
155 if item.len() > area.width as usize {
156 item = format!("{}...", &item[..area.width as usize - 3]);
157 }
158 buf.set_string(area.x, y, item, style);
159 y += 1;
160 }
161
162 if y < area.height + area.y {
163 let rect = Rect {
164 x: area.x,
165 y: y,
166 width: area.width,
167 height: area.height + area.y - y,
168 };
169
170 let paragraph = Paragraph::new(channel.description.clone())
171 .wrap(Wrap { trim: true })
172 .alignment(Alignment::Left)
173 .style(Style::default().fg(Color::Gray));
174
175 paragraph.render(rect, buf);
176 }
177 }
19178 ListItem::MiniVideo(video) => {
20179 let mut path = home::home_dir().expect("Cannot get your home directory");
21180 path.push(".cache");
@@ -318,7 +477,7 @@ impl Widget for ItemDisplay {
318477 if y > area.height + area.y - 1 {
319478 return;
320479 }
321
480
322481 if item.len() > area.width as usize {
323482 if item.len() > area.width as usize - 2 {
324483 for _ in area.width as usize - 3..item.len() {
@@ -347,7 +506,6 @@ impl Widget for ItemDisplay {
347506
348507 paragraph.render(area, buf);
349508 }
350
351509 }
352510 }
353511}
src/widgets/mod.rs +1 −1
@@ -1,4 +1,4 @@
1pub mod force_clear;
12pub mod horizontal_split;
23pub mod item_display;
34pub mod text_list;
4pub mod force_clear;
\ No newline at end of file