src/app/pages/item_info.rs

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

545 lines · 21092 bytes

  1use std::{
  2    collections::LinkedList,
  3    error::Error,
  4};
  5
  6use crate::{
  7    app::{
  8        app::App,
  9        config::{Action, PageCommand},
 10        pages::{channel::*, global::*},
 11    },
 12    functions::download_all_thumbnails,
 13    structs::{FullPlayList, FullVideo, Item, ListItem, Page, Row, RowItem, WatchHistory},
 14    traits::{ItemTrait, PageTrait},
 15    widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
 16};
 17use crossterm::event::KeyCode;
 18use tui::{
 19    backend::Backend,
 20    layout::{Constraint, Rect},
 21    style::{Color, Style},
 22    Frame,
 23};
 24
 25use super::global::GlobalItem;
 26
 27#[derive(Debug, Clone)]
 28pub enum ItemInfoItem {
 29    Unknown,
 30    Video(VideoItemInfo),
 31    PlayList(PlayListItemInfo),
 32}
 33
 34#[derive(Debug, Clone)]
 35pub struct VideoItemInfo {
 36    video: FullVideo,
 37    list: TextList,
 38    mode: Mode,
 39    commands: Vec<PageCommand>,
 40}
 41
 42#[derive(Debug, Clone)]
 43pub struct PlayListItemInfo {
 44    playlist: FullPlayList,
 45    video_view_list: TextList,
 46    playlist_view_list: TextList,
 47    display_view: PlayListDisplayView,
 48    mode: Mode,
 49    commands: Vec<PageCommand>,
 50}
 51
 52#[derive(Debug, Clone, Copy)]
 53pub enum PlayListDisplayView {
 54    VideoList,
 55    PlayListView,
 56}
 57
 58impl PlayListDisplayView {
 59    pub fn toggle(self) -> Self {
 60        match self {
 61            PlayListDisplayView::VideoList => PlayListDisplayView::PlayListView,
 62            PlayListDisplayView::PlayListView => PlayListDisplayView::VideoList,
 63        }
 64    }
 65}
 66
 67impl ItemTrait for ItemInfoItem {
 68    fn select(&mut self, app: App) -> (App, bool) {
 69        let selected = true;
 70
 71        (app, selected)
 72    }
 73
 74    fn selectable(&self) -> bool {
 75        true
 76    }
 77
 78    fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
 79        let action = match app.config.keybindings.0.get(&key) {
 80            Some(action) => *action,
 81            None => return (false, app),
 82        };
 83        match self {
 84            ItemInfoItem::Video(videoinfo) => match action {
 85                Action::Up => videoinfo.list.up(),
 86                Action::Down => videoinfo.list.down(),
 87                Action::FirstItem => videoinfo.list.selected = 0,
 88                Action::LastItem => videoinfo.list.selected = videoinfo.list.items.len() - 1,
 89                Action::Select => {
 90                    let command = &videoinfo.commands[videoinfo.list.selected];
 91
 92                    match command.command.as_str() {
 93                        "{toggle_mode}" => videoinfo.mode.toggle(),
 94                        "{goto_channel}" => {
 95                            let state = Channel::default();
 96                            let mut history = app.history.clone();
 97                            history.push(app.into());
 98
 99                            return (
100                                false,
101                                App {
102                                    history,
103                                    page: Page::Channel(
104                                        ChannelPage::Home,
105                                        videoinfo.video.channel_id.clone(),
106                                    ),
107                                    selectable: App::selectable(&state),
108                                    state,
109                                    ..Default::default()
110                                },
111                            );
112                        }
113                        _ => {
114                            match app.config.commands.0.get(&command.command) {
115                                Some(command) => {
116                                    let mut env = app.config.main.env.clone();
117
118                                    env.insert(
119                                        String::from("embed_url"),
120                                        format!(
121                                            "{}/embed/{}",
122                                            match videoinfo.mode {
123                                                Mode::Invidious => app.client.server.as_str(),
124                                                Mode::Youtube => "https://youtube.com",
125                                            },
126                                            videoinfo.video.video_id
127                                        ),
128                                    );
129
130                                    match command.run_command(&env) {
131                                        Some(e) => {
132                                            *app.message.lock().unwrap() =
133                                                Some(format!("Unknown variable `{}`", e))
134                                        }
135                                        None => {
136                                            *app.message.lock().unwrap() =
137                                                Some(command.message.clone())
138                                        }
139                                    }
140                                }
141                                None => {
142                                    *app.message.lock().unwrap() =
143                                        Some(format!("Unkown command `{}`", &command.command));
144                                }
145                            };
146                        }
147                    };
148                }
149                _ => {}
150            },
151
152            ItemInfoItem::PlayList(playlistinfo) => match playlistinfo.display_view {
153                PlayListDisplayView::PlayListView => match action {
154                    Action::Up => playlistinfo.playlist_view_list.up(),
155                    Action::Down => playlistinfo.playlist_view_list.down(),
156                    Action::FirstItem => playlistinfo.playlist_view_list.selected = 0,
157                    Action::LastItem => {
158                        playlistinfo.playlist_view_list.selected =
159                            playlistinfo.playlist_view_list.items.len() - 1
160                    }
161                    Action::Select => {
162                        let command =
163                            &playlistinfo.commands[playlistinfo.playlist_view_list.selected];
164
165                        match command.command.as_str() {
166                            "{toggle_mode}" => playlistinfo.mode.toggle(),
167                            "{goto_channel}" => {
168                                let state = Channel::default();
169                                let mut history = app.history.clone();
170                                history.push(app.into());
171
172                                return (
173                                    false,
174                                    App {
175                                        history,
176                                        page: Page::Channel(
177                                            ChannelPage::Home,
178                                            playlistinfo.playlist.playlist_id.clone(),
179                                        ),
180                                        selectable: App::selectable(&state),
181                                        state,
182                                        ..Default::default()
183                                    },
184                                );
185                            }
186
187                            "{switch_view}" => {
188                                playlistinfo.display_view = playlistinfo.display_view.toggle()
189                            }
190                            _ => {
191                                match app.config.commands.0.get(&command.command) {
192                                    Some(command) => {
193                                        let mut env = app.config.main.env.clone();
194
195                                        env.insert(
196                                            String::from("embed_url"),
197                                            format!(
198                                                "{}/playlist?list={}",
199                                                match playlistinfo.mode {
200                                                    Mode::Invidious => app.client.server.as_str(),
201                                                    Mode::Youtube => "https://youtube.com",
202                                                },
203                                                playlistinfo.playlist.playlist_id
204                                            ),
205                                        );
206
207                                        match command.run_command(&env) {
208                                            Some(e) => {
209                                                *app.message.lock().unwrap() =
210                                                    Some(format!("Unknown variable `{}`", e))
211                                            }
212                                            None => {
213                                                *app.message.lock().unwrap() =
214                                                    Some(command.message.clone())
215                                            }
216                                        }
217                                    }
218                                    None => {
219                                        *app.message.lock().unwrap() =
220                                            Some(format!("Unkown command `{}`", &command.command));
221                                    }
222                                };
223                            }
224                        };
225                    }
226
227                    _ => {}
228                },
229                PlayListDisplayView::VideoList => match action {
230                    Action::Up => playlistinfo.video_view_list.up(),
231                    Action::Down => playlistinfo.video_view_list.down(),
232                    Action::FirstItem => playlistinfo.video_view_list.selected = 0,
233                    Action::LastItem => {
234                        playlistinfo.video_view_list.selected =
235                            playlistinfo.video_view_list.items.len() - 1
236                    }
237                    Action::Select => match playlistinfo.video_view_list.selected {
238                        0 => {
239                            playlistinfo.display_view = playlistinfo.display_view.toggle();
240                        }
241
242                        x => {
243                            let state = ItemInfo::default();
244                            let mut history = app.history.clone();
245                            history.push(app.into());
246
247                            return (
248                                false,
249                                App {
250                                    history,
251                                    page: Page::ItemDisplay(DisplayItem::Video(
252                                        playlistinfo.playlist.videos[x - 1].video_id.clone(),
253                                    )),
254                                    selectable: App::selectable(&state),
255                                    state,
256                                    ..Default::default()
257                                },
258                            );
259                        }
260                    },
261
262                    _ => {}
263                },
264            },
265            _ => {}
266        }
267
268        (true, app)
269    }
270
271    fn load_item(
272        &self,
273        app: &App,
274        watch_history: &mut WatchHistory,
275    ) -> Result<Item, Box<dyn Error>> {
276        let mut this = self.clone();
277
278        if let ItemInfoItem::Unknown = this {
279            match &app.page {
280                Page::ItemDisplay(display_item) => match display_item {
281                    DisplayItem::Video(id) => {
282                        let mut list = TextList::default();
283                        let video: FullVideo = app.client.video(id, None)?.into();
284                        let _ = download_all_thumbnails(LinkedList::from([(
285                            video.video_thumbnail.clone(),
286                            video.video_id.clone(),
287                        )]));
288                        let commands = app
289                            .config
290                            .page_commands
291                            .0
292                            .get("item_info:video")
293                            .unwrap_or(&Vec::new())
294                            .clone();
295                        list.items(commands.iter().map(|item| item.label.to_string()).collect());
296
297                        let iteminfo = VideoItemInfo {
298                            video,
299                            list,
300                            mode: Mode::Youtube,
301                            commands,
302                        };
303
304                        watch_history.push(
305                            iteminfo.video.video_id.clone(),
306                            ListItem::FullVideo(iteminfo.video.clone()),
307                            &app.config,
308                        );
309
310                        this = ItemInfoItem::Video(iteminfo);
311                    }
312
313                    DisplayItem::PlayList(id) => {
314                        let mut videos_text_list = TextList::default();
315                        let mut playlist_text_list = TextList::default();
316                        let playlist: FullPlayList = app.client.playlist(id, None)?.into();
317                        let _ = download_all_thumbnails(
318                            playlist
319                                .videos
320                                .iter()
321                                .map(|v| (v.video_thumbnail.clone(), v.video_id.clone()))
322                                .collect(),
323                        );
324
325                        videos_text_list.items = vec![String::from("Swtich view")];
326                        videos_text_list
327                            .items
328                            .extend(playlist.videos.iter().map(|v| v.title.clone()));
329
330                        let commands = app
331                            .config
332                            .page_commands
333                            .0
334                            .get("item_info:playlist")
335                            .unwrap_or(&Vec::new())
336                            .clone();
337                        playlist_text_list
338                            .items(commands.iter().map(|item| item.label.to_string()).collect());
339
340                        let iteminfo = PlayListItemInfo {
341                            playlist: playlist,
342                            video_view_list: videos_text_list,
343                            playlist_view_list: playlist_text_list,
344                            mode: Mode::Youtube,
345                            display_view: PlayListDisplayView::PlayListView,
346                            commands,
347                        };
348
349                        watch_history.push(
350                            iteminfo.playlist.playlist_id.clone(),
351                            ListItem::FullPlayList(iteminfo.playlist.clone()),
352                            &app.config,
353                        );
354
355                        this = ItemInfoItem::PlayList(iteminfo);
356                    }
357                },
358
359                _ => {}
360            }
361        }
362        Ok(Item::ItemInfo(this))
363    }
364
365    fn render_item<B: Backend>(
366        &self,
367        frame: &mut Frame<B>,
368        rect: Rect,
369        app: App,
370        selected: bool,
371        hover: bool,
372        popup_focus: bool,
373        _: bool,
374    ) -> (bool, Option<Item>, App) {
375        let out = (false, None, app);
376        match self {
377            ItemInfoItem::Video(videoinfo) => {
378                let mut list = videoinfo.list.clone();
379
380                list.items.iter_mut().for_each(|item| match item.as_str() {
381                    "{mode}" => *item = format!("Mode: {}", videoinfo.mode),
382                    _ => {}
383                });
384                // list.items[videoinfo.list.items.len() - 1] = format!("Mode: {}", videoinfo.mode);
385
386                let split = HorizontalSplit::default()
387                    .percentages(vec![40, 60])
388                    .border_style(Style::default().fg(if selected {
389                        Color::LightBlue
390                    } else if hover {
391                        Color::LightRed
392                    } else {
393                        Color::Reset
394                    }));
395
396                let chunks = split.inner(rect);
397
398                list.area(chunks[1]);
399                if selected {
400                    list.selected_style(Style::default().fg(Color::LightRed));
401                } else {
402                    list.selected_style(Style::default().fg(Color::LightYellow));
403                }
404
405                frame.render_widget(split, rect);
406
407                if !popup_focus {
408                    let item_display = ItemDisplay {
409                        item: ListItem::FullVideo(videoinfo.video.clone()),
410                    };
411
412                    frame.render_widget(item_display, chunks[0]);
413                }
414
415                frame.render_widget(list, chunks[1]);
416            }
417
418            ItemInfoItem::PlayList(playlistinfo) => {
419                let split = HorizontalSplit::default()
420                    .percentages(vec![40, 60])
421                    .border_style(Style::default().fg(if selected {
422                        Color::LightBlue
423                    } else if hover {
424                        Color::LightRed
425                    } else {
426                        Color::Reset
427                    }));
428
429                let chunks = split.inner(rect);
430
431                frame.render_widget(split, rect);
432
433                if !popup_focus {
434                    let item_display = ItemDisplay {
435                        item: ListItem::FullPlayList(playlistinfo.playlist.clone()),
436                    };
437
438                    frame.render_widget(item_display, chunks[0]);
439                }
440
441                match playlistinfo.display_view {
442                    PlayListDisplayView::VideoList => {
443                        let mut list = playlistinfo.video_view_list.clone();
444                        list.area(chunks[1]);
445                        if selected {
446                            list.selected_style(Style::default().fg(Color::LightRed));
447                        } else {
448                            list.selected_style(Style::default().fg(Color::LightYellow));
449                        }
450
451                        frame.render_widget(list, chunks[1]);
452                    }
453                    PlayListDisplayView::PlayListView => {
454                        let mut list = playlistinfo.playlist_view_list.clone();
455
456                        list.items.iter_mut().for_each(|item| match item.as_str() {
457                            "{mode}" => *item = format!("Mode: {}", playlistinfo.mode),
458                            _ => {}
459                        });
460
461                        list.area(chunks[1]);
462
463                        if selected {
464                            list.selected_style(Style::default().fg(Color::LightRed));
465                        } else {
466                            list.selected_style(Style::default().fg(Color::LightYellow));
467                        }
468
469                        frame.render_widget(list, chunks[1]);
470                    }
471                }
472            }
473
474            ItemInfoItem::Unknown => {
475                let split = HorizontalSplit::default()
476                    .percentages(vec![40, 60])
477                    .border_style(Style::default().fg(if selected {
478                        Color::LightBlue
479                    } else if hover {
480                        Color::LightRed
481                    } else {
482                        Color::Reset
483                    }));
484
485                frame.render_widget(split, rect);
486            }
487        }
488        out
489    }
490}
491
492#[derive(Debug, Clone, PartialEq)]
493pub enum DisplayItem {
494    Video(String),
495    PlayList(String),
496}
497
498pub struct ItemInfo;
499
500impl PageTrait for ItemInfo {
501    fn message() -> String {
502        String::from("Loading item info...")
503    }
504
505    fn min() -> (u16, u16) {
506        (21, 12)
507    }
508
509    fn default() -> Vec<Row> {
510        vec![
511            Row {
512                items: vec![
513                    RowItem {
514                        item: Item::Global(GlobalItem::SearchBar),
515                        constraint: Constraint::Min(16),
516                    },
517                    RowItem {
518                        item: Item::Global(GlobalItem::SearchSettings),
519                        constraint: Constraint::Length(5),
520                    },
521                ],
522                centered: false,
523                height: Constraint::Length(3),
524            },
525            Row {
526                items: vec![RowItem {
527                    item: Item::ItemInfo(ItemInfoItem::Unknown),
528                    constraint: Constraint::Percentage(100),
529                }],
530                centered: false,
531                height: Constraint::Min(6),
532            },
533            Row {
534                items: vec![RowItem {
535                    item: Item::Global(GlobalItem::MessageBar),
536                    constraint: Constraint::Percentage(100),
537                }],
538                centered: false,
539                height: Constraint::Length(3),
540            },
541        ]
542    }
543}
544
545impl ItemInfoItem {}