src/app/pages/channel.rs

2512b334b421431b5e8577ab9c3031350fcd71bd
youtube-tui/src/app/pages/channel.rs history · blame · raw

481 lines · 17184 bytes

  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, config::Action},
 14    functions::download_all_thumbnails,
 15    structs::{
 16        FullChannel, Item, ListItem, MiniPlayList, MiniVideo, Page, Row, RowItem, WatchHistory,
 17    },
 18    traits::{ItemTrait, PageTrait},
 19    widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
 20};
 21
 22use super::{
 23    global::GlobalItem,
 24    item_info::{DisplayItem, ItemInfo},
 25};
 26
 27#[derive(Debug, Clone, Copy, PartialEq)]
 28pub enum ChannelPage {
 29    Home,
 30    Playlists,
 31    Videos,
 32}
 33
 34#[derive(Debug, Clone)]
 35pub enum ChannelItem {
 36    InfoDisplay(ChannelDisplayItem),
 37    SelectItems(ChannelPage),
 38}
 39
 40#[derive(Debug, Clone)]
 41pub enum ChannelDisplayItem {
 42    Playlists(Vec<MiniPlayList>, TextList),
 43    Videos(Vec<MiniVideo>, TextList),
 44    Home(FullChannel),
 45    Unknown,
 46}
 47
 48impl ItemTrait for ChannelItem {
 49    fn load_item(&self, app: &App, _: &mut WatchHistory) -> Result<Item, Box<dyn Error>> {
 50        let mut this = self.clone();
 51
 52        if let Page::Channel(channel_page, id) = &app.page {
 53            if let ChannelItem::InfoDisplay(displayitem) = &mut this {
 54                match channel_page {
 55                    ChannelPage::Home => {
 56                        let channel = app.client.channel(id, None)?;
 57                        let mut linked_list = LinkedList::new();
 58                        linked_list.push_back((
 59                            channel.authorThumbnails[4].url.clone(),
 60                            channel.authorId.clone(),
 61                        ));
 62                        let _ = download_all_thumbnails(linked_list);
 63
 64                        *displayitem = ChannelDisplayItem::Home(channel.into());
 65                    }
 66                    ChannelPage::Playlists => {
 67                        let mut textlist = TextList::default();
 68                        let playlists = app
 69                            .client
 70                            .channel_playlists(id, None)?
 71                            .playlists
 72                            .into_iter()
 73                            .map(|item| {
 74                                textlist.items.push(item.title.clone());
 75                                item.into()
 76                            })
 77                            .collect::<Vec<MiniPlayList>>();
 78
 79                        let mut linked_list = LinkedList::new();
 80                        for item in playlists.iter() {
 81                            if let Some(thumbnail) = &item.thumbnail {
 82                                linked_list
 83                                    .push_back((thumbnail.clone(), item.playlist_id.clone()));
 84                            }
 85                        }
 86                        let _ = download_all_thumbnails(linked_list);
 87
 88                        *displayitem = ChannelDisplayItem::Playlists(playlists, textlist);
 89                    }
 90
 91                    ChannelPage::Videos => {
 92                        let mut textlist = TextList::default();
 93                        let videos = app
 94                            .client
 95                            .channel_videos(id, None)?
 96                            .videos
 97                            .into_iter()
 98                            .map(|item| {
 99                                textlist.items.push(item.title.clone());
100                                item.into()
101                            })
102                            .collect::<Vec<MiniVideo>>();
103
104                        let mut linked_list = LinkedList::new();
105                        for item in videos.iter() {
106                            linked_list
107                                .push_back((item.video_thumbnail.clone(), item.video_id.clone()));
108                        }
109                        let _ = download_all_thumbnails(linked_list);
110
111                        *displayitem = ChannelDisplayItem::Videos(videos, textlist);
112                    }
113                }
114            }
115        }
116
117        Ok(Item::Channel(this))
118    }
119
120    fn render_item<B: Backend>(
121        // &mut self,
122        // frame: &mut Frame<B>,
123        // rect: Rect,
124        // selected: bool,
125        // hover: bool,
126        // popup_focus: bool,
127        // page: &Page,
128        &self,
129        frame: &mut Frame<B>,
130        rect: Rect,
131        app: App,
132        selected: bool,
133        hover: bool,
134        popup_focus: bool,
135        _: bool,
136    ) -> (bool, Option<Item>, App) {
137        let mut out = (false, None, app);
138
139        let mut style = Style::default().fg(if selected {
140            Color::LightBlue
141        } else if hover {
142            Color::LightRed
143        } else {
144            Color::Reset
145        });
146
147        match self {
148            ChannelItem::InfoDisplay(displayitem) => match displayitem {
149                ChannelDisplayItem::Unknown => {
150                    let block = Block::default()
151                        .border_type(BorderType::Rounded)
152                        .borders(Borders::ALL)
153                        .border_style(style);
154
155                    frame.render_widget(block, rect);
156                }
157                ChannelDisplayItem::Home(channel) => {
158                    let block = Block::default()
159                        .border_type(BorderType::Rounded)
160                        .borders(Borders::ALL)
161                        .border_style(style);
162
163                    let inner = block.inner(rect);
164                    frame.render_widget(block, rect);
165                    frame.render_widget(
166                        ItemDisplay {
167                            item: ListItem::FullChannel(channel.clone()),
168                        },
169                        inner,
170                    );
171                }
172                ChannelDisplayItem::Videos(videos, textlist) => {
173                    let split = HorizontalSplit::default()
174                        .percentages(vec![60, 40])
175                        .border_style(Style::default().fg(if selected {
176                            Color::LightBlue
177                        } else if hover {
178                            Color::LightRed
179                        } else {
180                            Color::Reset
181                        }));
182
183                    let chunks = split.inner(rect);
184
185                    frame.render_widget(split, rect);
186
187                    let mut textlist = textlist.clone();
188
189                    textlist.area(chunks[0]);
190
191                    let hold_textlist = if textlist.area == textlist.prev_area {
192                        None
193                    } else {
194                        Some(textlist.clone())
195                    };
196
197                    if selected {
198                        textlist.selected_style(Style::default().fg(Color::LightRed));
199                    } else {
200                        textlist.selected_style(Style::default().fg(Color::LightYellow));
201                    }
202
203                    if let Some(item) = videos.iter().nth(textlist.selected) {
204                        if !popup_focus {
205                            frame.render_widget(
206                                ItemDisplay {
207                                    item: ListItem::MiniVideo(item.clone()),
208                                },
209                                chunks[1],
210                            );
211                        }
212                    }
213
214                    frame.render_widget(textlist, chunks[0]);
215
216                    if let Some(textlist) = hold_textlist {
217                        out.1 = Some(Item::Channel(ChannelItem::InfoDisplay(
218                            ChannelDisplayItem::Videos(videos.clone(), textlist),
219                        )));
220                    }
221                }
222                ChannelDisplayItem::Playlists(playlists, textlist) => {
223                    let split = HorizontalSplit::default()
224                        .percentages(vec![60, 40])
225                        .border_style(Style::default().fg(if selected {
226                            Color::LightBlue
227                        } else if hover {
228                            Color::LightRed
229                        } else {
230                            Color::Reset
231                        }));
232
233                    let chunks = split.inner(rect);
234
235                    frame.render_widget(split, rect);
236
237                    let mut textlist = textlist.clone();
238
239                    textlist.area(chunks[0]);
240
241                    let hold_textlist = if textlist.area == textlist.prev_area {
242                        None
243                    } else {
244                        Some(textlist.clone())
245                    };
246
247                    if selected {
248                        textlist.selected_style(Style::default().fg(Color::LightRed));
249                    } else {
250                        textlist.selected_style(Style::default().fg(Color::LightYellow));
251                    }
252
253                    if let Some(item) = playlists.iter().nth(textlist.selected) {
254                        if !popup_focus {
255                            frame.render_widget(
256                                ItemDisplay {
257                                    item: ListItem::MiniPlayList(item.clone()),
258                                },
259                                chunks[1],
260                            );
261                        }
262                    }
263
264                    frame.render_widget(textlist, chunks[0]);
265
266                    if let Some(textlist) = hold_textlist {
267                        out.1 = Some(Item::Channel(ChannelItem::InfoDisplay(
268                            ChannelDisplayItem::Playlists(playlists.clone(), textlist),
269                        )));
270                    }
271                }
272            },
273            ChannelItem::SelectItems(selected_page) => {
274                if !hover {
275                    if let Page::Channel(channel_page, _) = &out.2.page {
276                        if *selected_page == *channel_page {
277                            style = style.fg(Color::LightYellow);
278                        }
279                    }
280                }
281
282                let block = Block::default()
283                    .border_type(BorderType::Rounded)
284                    .borders(Borders::ALL)
285                    .border_style(style);
286                let paragraph = Paragraph::new(format!("{:?}", selected_page))
287                    .block(block)
288                    .alignment(Alignment::Center);
289
290                frame.render_widget(paragraph, rect);
291            }
292        }
293        out
294    }
295
296    fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
297        let action = match app.config.keybindings.0.get(&key) {
298            Some(action) => action,
299            None => return (false, app),
300        };
301
302        match self {
303            ChannelItem::InfoDisplay(displayitem) => match displayitem {
304                ChannelDisplayItem::Videos(videos, textlist) => match action {
305                    Action::Up => {
306                        textlist.up();
307                    }
308                    Action::Down => {
309                        textlist.down();
310                    }
311                    Action::FirstItem => {
312                        textlist.selected = 0;
313                    }
314                    Action::LastItem => {
315                        textlist.selected = textlist.items.len() - 1;
316                    }
317                    Action::Select => {
318                        let state = ItemInfo::default();
319                        let mut history = app.history.clone();
320                        history.push(app.into());
321
322                        return (
323                            false,
324                            App {
325                                history,
326                                page: Page::ItemDisplay(DisplayItem::Video(
327                                    videos[textlist.selected].video_id.clone(),
328                                )),
329                                selectable: App::selectable(&state),
330                                state,
331                                ..Default::default()
332                            },
333                        );
334                    }
335                    _ => {}
336                },
337
338                ChannelDisplayItem::Playlists(playlists, textlist) => match action {
339                    Action::Up => {
340                        textlist.up();
341                    }
342                    Action::Down => {
343                        textlist.down();
344                    }
345                    Action::FirstItem => {
346                        textlist.selected = 0;
347                    }
348                    Action::LastItem => {
349                        textlist.selected = textlist.items.len() - 1;
350                    }
351                    Action::Select => {
352                        let state = ItemInfo::default();
353                        let mut history = app.history.clone();
354                        history.push(app.into());
355
356                        return (
357                            false,
358                            App {
359                                history,
360                                page: Page::ItemDisplay(DisplayItem::PlayList(
361                                    playlists[textlist.selected].playlist_id.clone(),
362                                )),
363                                selectable: App::selectable(&state),
364                                state,
365                                ..Default::default()
366                            },
367                        );
368                    }
369                    _ => {}
370                },
371
372                _ => unreachable!(),
373            },
374            _ => {
375                unreachable!()
376            }
377        }
378
379        (true, app)
380    }
381
382    fn select(&mut self, app: App) -> (App, bool) {
383        let cloned = self.clone();
384        match &cloned {
385            ChannelItem::InfoDisplay(_) => (app, true),
386            ChannelItem::SelectItems(tab) => {
387                if let Page::Channel(channel_page, id) = &app.page.clone() {
388                    if *tab == *channel_page {
389                        return (app, false);
390                    }
391
392                    let state = Channel::default();
393                    let mut history = app.history.clone();
394                    history.push(app.into());
395
396                    return (
397                        App {
398                            history,
399                            page: Page::Channel(tab.clone(), id.clone()),
400                            selectable: App::selectable(&state),
401                            state,
402                            ..Default::default()
403                        },
404                        false,
405                    );
406                } else {
407                    (app, false)
408                }
409            }
410        }
411    }
412
413    fn selectable(&self) -> bool {
414        true
415    }
416}
417
418pub struct Channel;
419
420impl PageTrait for Channel {
421    fn message() -> String {
422        String::from("Loading channel info...")
423    }
424
425    fn min() -> (u16, u16) {
426        (45, 15)
427    }
428
429    fn default() -> Vec<Row> {
430        vec![
431            Row {
432                items: vec![
433                    RowItem {
434                        item: Item::Global(GlobalItem::SearchBar),
435                        constraint: Constraint::Min(16),
436                    },
437                    RowItem {
438                        item: Item::Global(GlobalItem::SearchSettings),
439                        constraint: Constraint::Length(5),
440                    },
441                ],
442                centered: false,
443                height: Constraint::Length(3),
444            },
445            Row {
446                items: vec![
447                    RowItem {
448                        item: Item::Channel(ChannelItem::SelectItems(ChannelPage::Home)),
449                        constraint: Constraint::Length(15),
450                    },
451                    RowItem {
452                        item: Item::Channel(ChannelItem::SelectItems(ChannelPage::Videos)),
453                        constraint: Constraint::Length(15),
454                    },
455                    RowItem {
456                        item: Item::Channel(ChannelItem::SelectItems(ChannelPage::Playlists)),
457                        constraint: Constraint::Length(15),
458                    },
459                ],
460                centered: true,
461                height: Constraint::Length(3),
462            },
463            Row {
464                items: vec![RowItem {
465                    item: Item::Channel(ChannelItem::InfoDisplay(ChannelDisplayItem::Unknown)),
466                    constraint: Constraint::Percentage(100),
467                }],
468                centered: false,
469                height: Constraint::Min(6),
470            },
471            Row {
472                items: vec![RowItem {
473                    item: Item::Global(GlobalItem::MessageBar),
474                    constraint: Constraint::Percentage(100),
475                }],
476                centered: false,
477                height: Constraint::Length(3),
478            },
479        ]
480    }
481}