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