src/app/pages/search.rs

388 lines · 14529 bytes

  1use std::{collections::LinkedList, error::Error};
  2
  3use crossterm::event::KeyEvent;
  4use invidious::structs::hidden::SearchItem as InvidiousSearchItem;
  5use tui::{
  6    backend::Backend,
  7    layout::Rect,
  8    style::{Color, Style},
  9    Frame,
 10};
 11
 12use crate::{
 13    app::{
 14        app::{App, AppNoState},
 15        config::{
 16            Action, ConstraintTransitional, ItemTransitional, LayoutConfig, RowItemTransitional,
 17            RowTransitional, SearchItemTransitional,
 18        },
 19    },
 20    functions::download_all_thumbnails,
 21    structs::{Item, ListItem, MiniChannel, MiniPlayList, MiniVideo, Page, WatchHistory},
 22    traits::{ItemTrait, PageTrait},
 23    widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
 24};
 25
 26use super::{
 27    channel::ChannelPage, global::GlobalItem, item_info::DisplayItem,
 28    main_menu::textlist_from_video_list,
 29};
 30
 31#[derive(Debug, Clone)]
 32pub enum SearchItem {
 33    Search {
 34        results: Option<LinkedList<ListItem>>,
 35        text_list: TextList,
 36    },
 37}
 38
 39impl ItemTrait for SearchItem {
 40    fn select(&mut self, app: App) -> (App, bool) {
 41        (app, true)
 42    }
 43
 44    fn selectable(&self) -> bool {
 45        true
 46    }
 47
 48    fn key_input(&mut self, key: KeyEvent, app: App) -> (bool, App) {
 49        let action = match app.config.keybindings.0.get(&key) {
 50            Some(action) => action,
 51            None => return (false, app),
 52        };
 53        match self {
 54            SearchItem::Search { results, text_list } => match action {
 55                Action::Up => text_list.up(),
 56                Action::Down => text_list.down(),
 57                Action::FirstItem => text_list.first(),
 58                Action::LastItem => text_list.last(),
 59                Action::Select => {
 60                    if let Some(results_unwrapped) = results {
 61                        match results_unwrapped.iter().nth(text_list.selected).unwrap() {
 62                            ListItem::PageTurner(b) => {
 63                                let new_page_no;
 64                                if *b {
 65                                    new_page_no = app.page_no + 1;
 66                                } else {
 67                                    new_page_no = app.page_no - 1;
 68                                }
 69
 70                                *results = None;
 71                                *text_list = TextList::default();
 72
 73                                let state = app.config.layouts.search.clone().into();
 74                                let mut history = app.history.clone();
 75                                let search_text = app.search_text.clone();
 76                                let search_settings = app.search_settings.clone();
 77                                history.push(app.into());
 78
 79                                return (
 80                                    false,
 81                                    App {
 82                                        history,
 83                                        page: Page::Search,
 84                                        selectable: App::selectable(&state),
 85                                        state,
 86                                        search_text,
 87                                        search_settings,
 88                                        load: true,
 89                                        page_no: new_page_no,
 90                                        ..Default::default()
 91                                    },
 92                                );
 93                            }
 94
 95                            ListItem::MiniVideo(video) => {
 96                                let state = app.config.layouts.item_info.clone().into();
 97                                let mut history = app.history.clone();
 98                                history.push(app.into());
 99
100                                return (
101                                    false,
102                                    App {
103                                        history,
104                                        page: Page::ItemDisplay(DisplayItem::Video(
105                                            video.video_id.clone(),
106                                        )),
107                                        selectable: App::selectable(&state),
108                                        state,
109                                        ..Default::default()
110                                    },
111                                );
112                            }
113
114                            ListItem::MiniPlayList(playlist) => {
115                                let state = app.config.layouts.item_info.clone().into();
116                                let mut history = app.history.clone();
117                                history.push(app.into());
118
119                                return (
120                                    false,
121                                    App {
122                                        history,
123                                        page: Page::ItemDisplay(DisplayItem::PlayList(
124                                            playlist.playlist_id.clone(),
125                                        )),
126                                        selectable: App::selectable(&state),
127                                        state,
128                                        ..Default::default()
129                                    },
130                                );
131                            }
132
133                            ListItem::MiniChannel(channel) => {
134                                let state = app.config.layouts.channel.clone().into();
135                                let mut history = app.history.clone();
136                                history.push(app.into());
137
138                                return (
139                                    false,
140                                    App {
141                                        history,
142                                        page: Page::Channel(
143                                            ChannelPage::Home,
144                                            channel.author_id.clone(),
145                                        ),
146                                        selectable: App::selectable(&state),
147                                        state,
148                                        ..Default::default()
149                                    },
150                                );
151                            }
152
153                            _ => {}
154                        }
155                    }
156                }
157                _ => {}
158            },
159        }
160
161        (true, app)
162    }
163
164    fn load_item(&self, app: &App, _: &mut WatchHistory) -> Result<Item, Box<dyn Error>> {
165        let mut this = self.clone();
166
167        match &mut this {
168            SearchItem::Search { results, text_list } => {
169                // panic!("got here");
170
171                let mut args = vec![app.search_text.clone()];
172                args.extend(app.search_settings.clone().to_vec());
173
174                let invidious_results = app
175                    .client
176                    .search(Some(&format!(
177                        "page={}&q={}",
178                        app.page_no,
179                        args.join("&").as_str()
180                    )))?
181                    .items;
182
183                let mut items = LinkedList::new();
184
185                for item in invidious_results {
186                    match item {
187                        InvidiousSearchItem::Video {
188                            title: _,
189                            videoId: _,
190                            author: _,
191                            authorId: _,
192                            authorUrl: _,
193                            lengthSeconds: _,
194                            videoThumbnails: _,
195                            description: _,
196                            descriptionHtml: _,
197                            viewCount: _,
198                            published: _,
199                            publishedText: _,
200                            liveNow: _,
201                            paid: _,
202                            premium: _,
203                        } => {
204                            items.push_back(ListItem::MiniVideo(MiniVideo::from(item)));
205                        }
206
207                        InvidiousSearchItem::Playlist {
208                            title: _,
209                            playlistId: _,
210                            author: _,
211                            authorId: _,
212                            authorUrl: _,
213                            videoCount: _,
214                            videos: _,
215                        } => {
216                            items.push_back(ListItem::MiniPlayList(MiniPlayList::from(item)));
217                        }
218
219                        InvidiousSearchItem::Channel {
220                            author: _,
221                            authorId: _,
222                            authorUrl: _,
223                            authorThumbnails: _,
224                            subCount: _,
225                            videoCount: _,
226                            description: _,
227                            descriptionHtml: _,
228                        } => {
229                            items.push_back(ListItem::MiniChannel(MiniChannel::from(item)));
230                        }
231
232                        _ => {}
233                    }
234                }
235
236                let mut minimum_length = 0;
237
238                if app.page_no != 1 {
239                    minimum_length += 1;
240                    items.push_front(ListItem::PageTurner(false));
241                }
242
243                if items.len() != minimum_length {
244                    items.push_back(ListItem::PageTurner(true));
245                }
246
247                text_list.items = textlist_from_video_list(&items);
248
249                let mut thumbnails = LinkedList::new();
250
251                for item in items.iter() {
252                    match item {
253                        ListItem::MiniVideo(video) => {
254                            thumbnails
255                                .push_back((video.video_thumbnail.clone(), video.video_id.clone()));
256                        }
257
258                        ListItem::MiniPlayList(playlist) => {
259                            if let Some(thumbnail) = &playlist.thumbnail {
260                                thumbnails
261                                    .push_back((thumbnail.clone(), playlist.playlist_id.clone()));
262                            }
263                        }
264
265                        ListItem::MiniChannel(channel) => {
266                            thumbnails.push_back((
267                                format!("https:{}", channel.thumbnail.clone()),
268                                channel.author_id.clone(),
269                            ));
270
271                            // panic!("{:?}", channel.thumbnail.clone());
272                        }
273
274                        _ => {}
275                    }
276                }
277
278                if app.config.main.display_thumbnails {
279                    let _ = download_all_thumbnails(thumbnails);
280                }
281
282                *results = Some(items);
283            }
284        }
285
286        Ok(Item::Search(this))
287    }
288
289    fn render_item<B: Backend>(
290        &mut self,
291        frame: &mut Frame<B>,
292        rect: Rect,
293        app: AppNoState,
294        selected: bool,
295        hover: bool,
296        popup_focus: bool,
297        popup_render: bool,
298    ) -> (bool, AppNoState) {
299        let out = (false, app);
300
301        if popup_render {
302            return out;
303        }
304
305        match self {
306            SearchItem::Search { results, text_list } => {
307                let split = HorizontalSplit::default()
308                    .percentages(vec![60, 40])
309                    .border_style(Style::default().fg(if selected {
310                        Color::LightBlue
311                    } else if hover {
312                        Color::LightRed
313                    } else {
314                        Color::Reset
315                    }));
316
317                let chunks = split.inner(rect);
318
319                frame.render_widget(split, rect);
320
321                text_list.area(chunks[0]);
322
323                let mut text_list = text_list.clone();
324
325                if let Some(result) = results {
326                    if let Some(item) = result.iter().nth(text_list.selected) {
327                        if !popup_focus {
328                            frame.render_widget(ItemDisplay { item: item.clone() }, chunks[1]);
329                        }
330                    }
331                }
332
333                if selected {
334                    text_list.selected_style(Style::default().fg(Color::LightRed));
335                } else {
336                    text_list.selected_style(Style::default().fg(Color::LightYellow));
337                }
338
339                frame.render_widget(text_list, chunks[0]);
340            }
341        }
342
343        out
344    }
345}
346
347pub struct Search;
348
349impl PageTrait for Search {
350    fn default() -> LayoutConfig {
351        LayoutConfig {
352            layout: vec![
353                RowTransitional {
354                    items: vec![
355                        RowItemTransitional {
356                            item: ItemTransitional::Global(GlobalItem::SearchBar),
357                            constraint: ConstraintTransitional::Min(16),
358                        },
359                        RowItemTransitional {
360                            item: ItemTransitional::Global(GlobalItem::SearchSettings),
361                            constraint: ConstraintTransitional::Length(5),
362                        },
363                    ],
364                    centered: false,
365                    height: ConstraintTransitional::Length(3),
366                },
367                RowTransitional {
368                    items: vec![RowItemTransitional {
369                        item: ItemTransitional::Search(SearchItemTransitional::Search),
370                        constraint: ConstraintTransitional::Percentage(100),
371                    }],
372                    centered: false,
373                    height: ConstraintTransitional::Min(6),
374                },
375                RowTransitional {
376                    items: vec![RowItemTransitional {
377                        item: ItemTransitional::Global(GlobalItem::MessageBar),
378                        constraint: ConstraintTransitional::Percentage(100),
379                    }],
380                    centered: false,
381                    height: ConstraintTransitional::Length(3),
382                },
383            ],
384            min: (45, 12),
385            message: String::from("Loading search results..."),
386        }
387    }
388}