src/app/pages/item_info.rs

9aedf4a98dfbe60cee47b4e673a37437e309f462
youtube-tui/src/app/pages/item_info.rs history · blame · raw

533 lines · 21029 bytes

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