src/config/search.rs

384 lines · 10348 bytes

  1use std::fmt::Display;
  2
  3use crate::global::{structs::Message, traits::*};
  4use serde::{Deserialize, Serialize};
  5use typemap::Key;
  6use urlencoding::encode;
  7
  8// can be turned into URL Params for the search term with filters
  9/// Search query & filters
 10#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
 11pub struct Search {
 12    pub query: String,
 13    pub filters: SearchFilters,
 14    pub page: u16,
 15}
 16
 17impl Default for Search {
 18    fn default() -> Self {
 19        Self {
 20            query: String::new(),
 21            filters: SearchFilters::default(),
 22            page: 1,
 23        }
 24    }
 25}
 26
 27impl Key for Search {
 28    type Value = Self;
 29}
 30
 31impl ConfigTrait for Search {
 32    const LABEL: &'static str = "search";
 33}
 34
 35impl Display for Search {
 36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 37        f.write_fmt(format_args!(
 38            "{}&page={}",
 39            [
 40                format!("q={}", encode(&self.query)),
 41                self.filters.sort.as_url_string(),
 42                self.filters.date.as_url_string(),
 43                self.filters.duration.as_url_string(),
 44                self.filters.r#type.as_url_string()
 45            ]
 46            .join("&"),
 47            self.page
 48        ))
 49    }
 50}
 51
 52/// Search filters, read comments for function docs
 53#[derive(Default, Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
 54pub struct SearchFilters {
 55    pub sort: SearchFilterSort,
 56    pub date: SearchFilterDate,
 57    pub duration: SearchFilterDuration,
 58    pub r#type: SearchFilterType,
 59}
 60
 61// These functions are used in the search filter item
 62// Think of the ordering of stuff in the popup menu
 63impl SearchFilters {
 64    // This function returns [(Option name, [Options])]
 65    // Option name is a string like "sory by" and "type"
 66    // Options are the options that you can select like "relevance" and "upload date" for sorting
 67    pub fn get_all() -> [(&'static str, Vec<&'static str>); 5] {
 68        [
 69            (SearchFilterSort::NAME, SearchFilterSort::ordering()),
 70            (SearchFilterDate::NAME, SearchFilterDate::ordering()),
 71            (SearchFilterDuration::NAME, SearchFilterDuration::ordering()),
 72            (SearchFilterType::NAME, SearchFilterType::ordering()),
 73            ("Reset filters", vec!["Are you sure?"]),
 74        ]
 75    }
 76
 77    // uses the index of the selected option name to get the index of the selected option
 78    // aka using the hover location of the left textlist to get the hover location of the right text list
 79    pub fn get_selected(&self, index: usize) -> usize {
 80        match index {
 81            0 => self.sort.selected_index(),
 82            1 => self.date.selected_index(),
 83            2 => self.duration.selected_index(),
 84            3 => self.r#type.selected_index(),
 85            4 => 0,
 86            _ => unreachable!("`{index}` is not a valid index"),
 87        }
 88    }
 89
 90    // saves the settings for a filter given the index of the option (among other options) and the index of the selected options
 91    //                           v left textlist   v right textlist
 92    pub fn set_index(&mut self, index_at: usize, set_index: usize, message: &mut Message) {
 93        match index_at {
 94            0 => self.sort = SearchFilterSort::at_index(set_index),
 95            1 => self.date = SearchFilterDate::at_index(set_index),
 96            2 => self.duration = SearchFilterDuration::at_index(set_index),
 97            3 => self.r#type = SearchFilterType::at_index(set_index),
 98            4 => {
 99                if set_index == 0 {
100                    self.reset(message)
101                } else {
102                    unreachable!("index can only be `0` for option `4` (reset all)")
103                }
104            }
105            _ => unreachable!("`{index_at}` is not a valid index"),
106        }
107    }
108
109    pub fn reset(&mut self, message: &mut Message) {
110        *self = Self::default();
111        *message = Message::Success(String::from("Search filters has been reset"));
112    }
113}
114
115#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
116#[derive(Default)]
117pub enum SearchFilterSort {
118    #[default]
119    Relevance,
120    Rating,
121    Date,
122    Views,
123}
124
125#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
126#[derive(Default)]
127pub enum SearchFilterDate {
128    #[default]
129    None,
130    Hour,
131    Day,
132    Week,
133    Month,
134    Year,
135}
136
137#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
138#[derive(Default)]
139pub enum SearchFilterDuration {
140    #[default]
141    None,
142    Short,
143    Medium,
144    Long,
145}
146
147#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
148#[derive(Default)]
149pub enum SearchFilterType {
150    #[default]
151    All,
152    Video,
153    Channel,
154    Playlist,
155}
156
157
158
159
160
161impl Display for SearchFilterSort {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        f.write_str(match self {
164            Self::Relevance => "relevance",
165            Self::Rating => "rating",
166            Self::Date => "date",
167            Self::Views => "views",
168        })
169    }
170}
171
172impl Display for SearchFilterDate {
173    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174        f.write_str(match self {
175            Self::None => "none",
176            Self::Hour => "hour",
177            Self::Day => "day",
178            Self::Week => "week",
179            Self::Month => "month",
180            Self::Year => "year",
181        })
182    }
183}
184
185impl Display for SearchFilterDuration {
186    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187        f.write_str(match self {
188            Self::None => "none",
189            Self::Short => "short",
190            Self::Medium => "medium",
191            Self::Long => "long",
192        })
193    }
194}
195
196impl Display for SearchFilterType {
197    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198        f.write_str(match self {
199            Self::All => "all",
200            Self::Video => "video",
201            Self::Channel => "channel",
202            Self::Playlist => "playlist",
203        })
204    }
205}
206
207impl AsUrlString for SearchFilterSort {
208    const TAG: &'static str = "sort";
209}
210
211impl AsUrlString for SearchFilterDate {
212    const TAG: &'static str = "date";
213}
214
215impl AsUrlString for SearchFilterDuration {
216    const TAG: &'static str = "duration";
217}
218
219impl AsUrlString for SearchFilterType {
220    const TAG: &'static str = "type";
221}
222
223const SORT_ORDERING: [SearchFilterSort; 4] = [
224    SearchFilterSort::Relevance,
225    SearchFilterSort::Rating,
226    SearchFilterSort::Date,
227    SearchFilterSort::Views,
228];
229const DATE_ORDERING: [SearchFilterDate; 6] = [
230    SearchFilterDate::None,
231    SearchFilterDate::Hour,
232    SearchFilterDate::Day,
233    SearchFilterDate::Week,
234    SearchFilterDate::Month,
235    SearchFilterDate::Year,
236];
237const DURATION_ORDERING: [SearchFilterDuration; 4] = [
238    SearchFilterDuration::None,
239    SearchFilterDuration::Short,
240    SearchFilterDuration::Medium,
241    SearchFilterDuration::Long,
242];
243const TYPE_ORDERING: [SearchFilterType; 4] = [
244    SearchFilterType::All,
245    SearchFilterType::Video,
246    SearchFilterType::Channel,
247    SearchFilterType::Playlist,
248];
249
250impl SearchFilterItem for SearchFilterSort {
251    const NAME: &'static str = "Sort by";
252
253    fn option_name(&self) -> &'static str {
254        match self {
255            Self::Relevance => "Relevance",
256            Self::Rating => "Rating",
257            Self::Date => "Upload date",
258            Self::Views => "View count",
259        }
260    }
261
262    fn ordering() -> Vec<&'static str> {
263        SORT_ORDERING
264            .iter()
265            .map(|item| item.option_name())
266            .collect::<Vec<_>>()
267    }
268
269    fn selected_index(&self) -> usize {
270        match self {
271            Self::Relevance => 0,
272            Self::Rating => 1,
273            Self::Date => 2,
274            Self::Views => 3,
275        }
276    }
277
278    fn at_index(index: usize) -> Self {
279        SORT_ORDERING[index]
280    }
281}
282
283impl SearchFilterItem for SearchFilterDate {
284    const NAME: &'static str = "Upload date";
285
286    fn option_name(&self) -> &'static str {
287        match self {
288            Self::None => "Any date",
289            Self::Hour => "Last hour",
290            Self::Day => "Today",
291            Self::Week => "This week",
292            Self::Month => "This month",
293            Self::Year => "This year",
294        }
295    }
296
297    fn ordering() -> Vec<&'static str> {
298        DATE_ORDERING
299            .iter()
300            .map(|item| item.option_name())
301            .collect::<Vec<_>>()
302    }
303
304    fn selected_index(&self) -> usize {
305        match self {
306            Self::None => 0,
307            Self::Hour => 1,
308            Self::Day => 2,
309            Self::Week => 3,
310            Self::Month => 4,
311            Self::Year => 5,
312        }
313    }
314
315    fn at_index(index: usize) -> Self {
316        DATE_ORDERING[index]
317    }
318}
319
320impl SearchFilterItem for SearchFilterDuration {
321    const NAME: &'static str = "Duration";
322
323    fn option_name(&self) -> &'static str {
324        match self {
325            Self::None => "Any duration",
326            Self::Short => "Short (< 4 minutes)",
327            Self::Medium => "Medium (4 - 20 minutes)",
328            Self::Long => "Long (> 20 minutes)",
329        }
330    }
331
332    fn ordering() -> Vec<&'static str> {
333        DURATION_ORDERING
334            .iter()
335            .map(|item| item.option_name())
336            .collect::<Vec<_>>()
337    }
338
339    fn selected_index(&self) -> usize {
340        match self {
341            Self::None => 0,
342            Self::Short => 1,
343            Self::Medium => 2,
344            Self::Long => 3,
345        }
346    }
347
348    fn at_index(index: usize) -> Self {
349        DURATION_ORDERING[index]
350    }
351}
352
353impl SearchFilterItem for SearchFilterType {
354    const NAME: &'static str = "Type";
355
356    fn option_name(&self) -> &'static str {
357        match self {
358            Self::All => "Any type",
359            Self::Video => "Video",
360            Self::Channel => "Channel",
361            Self::Playlist => "Playlist",
362        }
363    }
364
365    fn ordering() -> Vec<&'static str> {
366        TYPE_ORDERING
367            .iter()
368            .map(|item| item.option_name())
369            .collect::<Vec<_>>()
370    }
371
372    fn selected_index(&self) -> usize {
373        match self {
374            Self::All => 0,
375            Self::Video => 1,
376            Self::Channel => 2,
377            Self::Playlist => 3,
378        }
379    }
380
381    fn at_index(index: usize) -> Self {
382        TYPE_ORDERING[index]
383    }
384}