src/app/pages/channel.rs

465 lines · 17514 bytes

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