src/config/search.rs

394 lines · 10558 bytes

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