Skip to main content

kodik_api/
query.rs

1//! Типизированные параметры всех ресурсов Kodik API.
2//!
3//! Все строки с несколькими значениями сериализуются через запятую, как требует API.
4
5use std::fmt;
6
7use crate::error::{Error, Result};
8
9/// HTTP-способ передачи параметров к Kodik API.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum RequestMethod {
12    /// Параметры передаются в URL как query string. Это значение по умолчанию.
13    #[default]
14    Get,
15    /// Параметры передаются в теле `application/x-www-form-urlencoded`.
16    Post,
17}
18
19/// Тип материала, который Kodik принимает в параметре `types`.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum ContentType {
22    ForeignMovie,
23    SovietCartoon,
24    ForeignCartoon,
25    RussianCartoon,
26    Anime,
27    RussianMovie,
28    CartoonSerial,
29    DocumentarySerial,
30    RussianSerial,
31    ForeignSerial,
32    AnimeSerial,
33    MultiPartFilm,
34}
35
36impl ContentType {
37    /// Строковое значение Kodik API.
38    pub const fn as_str(self) -> &'static str {
39        match self {
40            Self::ForeignMovie => "foreign-movie",
41            Self::SovietCartoon => "soviet-cartoon",
42            Self::ForeignCartoon => "foreign-cartoon",
43            Self::RussianCartoon => "russian-cartoon",
44            Self::Anime => "anime",
45            Self::RussianMovie => "russian-movie",
46            Self::CartoonSerial => "cartoon-serial",
47            Self::DocumentarySerial => "documentary-serial",
48            Self::RussianSerial => "russian-serial",
49            Self::ForeignSerial => "foreign-serial",
50            Self::AnimeSerial => "anime-serial",
51            Self::MultiPartFilm => "multi-part-film",
52        }
53    }
54}
55
56impl fmt::Display for ContentType {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        f.write_str(self.as_str())
59    }
60}
61
62/// Тип перевода в Kodik.
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub enum TranslationType {
65    Voice,
66    Subtitles,
67}
68
69impl TranslationType {
70    pub const fn as_str(self) -> &'static str {
71        match self {
72            Self::Voice => "voice",
73            Self::Subtitles => "subtitles",
74        }
75    }
76}
77
78impl fmt::Display for TranslationType {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        f.write_str(self.as_str())
81    }
82}
83
84/// Поле внешнего идентификатора, требуемое параметрами `has_field` и `has_field_and`.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum RequiredField {
87    KinopoiskId,
88    ImdbId,
89    MdlId,
90    WorldartLink,
91    ShikimoriId,
92}
93
94impl RequiredField {
95    pub const fn as_str(self) -> &'static str {
96        match self {
97            Self::KinopoiskId => "kinopoisk_id",
98            Self::ImdbId => "imdb_id",
99            Self::MdlId => "mdl_id",
100            Self::WorldartLink => "worldart_link",
101            Self::ShikimoriId => "shikimori_id",
102        }
103    }
104}
105
106impl fmt::Display for RequiredField {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        f.write_str(self.as_str())
109    }
110}
111
112/// Типы списка жанров, который должен вернуть `/genres`.
113#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
114pub enum GenreSource {
115    /// Жанры КиноПоиска — значение API по умолчанию.
116    #[default]
117    Kinopoisk,
118    Shikimori,
119    MyDramaList,
120    All,
121}
122
123impl GenreSource {
124    pub const fn as_str(self) -> &'static str {
125        match self {
126            Self::Kinopoisk => "kinopoisk",
127            Self::Shikimori => "shikimori",
128            Self::MyDramaList => "mydramalist",
129            Self::All => "all",
130        }
131    }
132}
133
134impl fmt::Display for GenreSource {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        f.write_str(self.as_str())
137    }
138}
139
140/// Направление сортировки `/list`.
141#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
142pub enum SortOrder {
143    Asc,
144    /// Убывание — значение API по умолчанию.
145    #[default]
146    Desc,
147}
148
149impl SortOrder {
150    pub const fn as_str(self) -> &'static str {
151        match self {
152            Self::Asc => "asc",
153            Self::Desc => "desc",
154        }
155    }
156}
157
158impl fmt::Display for SortOrder {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        f.write_str(self.as_str())
161    }
162}
163
164/// Поле сортировки `/list`.
165#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
166pub enum ListSort {
167    Year,
168    CreatedAt,
169    /// Время обновления — значение API по умолчанию.
170    #[default]
171    UpdatedAt,
172    KinopoiskRating,
173    ImdbRating,
174    ShikimoriRating,
175}
176
177impl ListSort {
178    pub const fn as_str(self) -> &'static str {
179        match self {
180            Self::Year => "year",
181            Self::CreatedAt => "created_at",
182            Self::UpdatedAt => "updated_at",
183            Self::KinopoiskRating => "kinopoisk_rating",
184            Self::ImdbRating => "imdb_rating",
185            Self::ShikimoriRating => "shikimori_rating",
186        }
187    }
188}
189
190impl fmt::Display for ListSort {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        f.write_str(self.as_str())
193    }
194}
195
196/// Сортировка строкового справочника: стран, жанров, качеств и озвучек.
197#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
198pub enum LabelSort {
199    /// По названию — значение API по умолчанию.
200    #[default]
201    Title,
202    Count,
203}
204
205impl LabelSort {
206    pub const fn as_str(self) -> &'static str {
207        match self {
208            Self::Title => "title",
209            Self::Count => "count",
210        }
211    }
212}
213
214impl fmt::Display for LabelSort {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        f.write_str(self.as_str())
217    }
218}
219
220/// Сортировка списка лет.
221#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
222pub enum YearSort {
223    /// По году — значение API по умолчанию.
224    #[default]
225    Year,
226    Count,
227}
228
229impl YearSort {
230    pub const fn as_str(self) -> &'static str {
231        match self {
232            Self::Year => "year",
233            Self::Count => "count",
234        }
235    }
236}
237
238impl fmt::Display for YearSort {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        f.write_str(self.as_str())
241    }
242}
243
244/// Общие фильтры материалов, доступные в `/years`, `/genres`, `/countries`,
245/// `/qualities/v2`, `/translations/v2`, `/list` и `/search`.
246///
247/// Поля с суффиксом `_and` требуют наличия **всех** перечисленных значений.
248/// Их аналоги без суффикса используют семантику «хотя бы одно». Диапазоны
249/// (`duration`, рейтинги и `minimal_age`) нужно задавать строкой: `"40-80"`.
250#[derive(Clone, Debug, Default, PartialEq, Eq)]
251pub struct Filters {
252    pub types: Vec<ContentType>,
253    pub year: Vec<i32>,
254    pub translation_ids: Vec<u64>,
255    pub block_translations: Vec<u64>,
256    pub translation_type: Option<TranslationType>,
257    pub has_field: Vec<RequiredField>,
258    pub has_field_and: Vec<RequiredField>,
259    pub camrip: Option<bool>,
260    pub lgbt: Option<bool>,
261    pub countries: Vec<String>,
262    pub countries_and: Vec<String>,
263    pub genres: Vec<String>,
264    pub genres_and: Vec<String>,
265    pub anime_genres: Vec<String>,
266    pub anime_genres_and: Vec<String>,
267    pub drama_genres: Vec<String>,
268    pub drama_genres_and: Vec<String>,
269    pub all_genres: Vec<String>,
270    pub all_genres_and: Vec<String>,
271    pub duration: Option<String>,
272    pub kinopoisk_rating: Option<String>,
273    pub imdb_rating: Option<String>,
274    pub shikimori_rating: Option<String>,
275    pub mydramalist_rating: Option<String>,
276    pub actors: Vec<String>,
277    pub actors_and: Vec<String>,
278    pub directors: Vec<String>,
279    pub directors_and: Vec<String>,
280    pub producers: Vec<String>,
281    pub producers_and: Vec<String>,
282    pub writers: Vec<String>,
283    pub writers_and: Vec<String>,
284    pub composers: Vec<String>,
285    pub composers_and: Vec<String>,
286    pub editors: Vec<String>,
287    pub editors_and: Vec<String>,
288    pub designers: Vec<String>,
289    pub designers_and: Vec<String>,
290    pub operators: Vec<String>,
291    pub operators_and: Vec<String>,
292    pub rating_mpaa: Vec<String>,
293    pub minimal_age: Option<String>,
294    pub anime_kind: Vec<String>,
295    pub mydramalist_tags: Vec<String>,
296    pub mydramalist_tags_and: Vec<String>,
297    pub anime_status: Vec<String>,
298    pub drama_status: Vec<String>,
299    pub all_status: Vec<String>,
300    pub anime_studios: Vec<String>,
301    pub anime_studios_and: Vec<String>,
302    pub anime_licensed_by: Vec<String>,
303    pub anime_licensed_by_and: Vec<String>,
304}
305
306impl Filters {
307    /// Добавляет фильтр по типам материалов.
308    pub fn with_types(mut self, values: impl IntoIterator<Item = ContentType>) -> Self {
309        self.types.extend(values);
310        self
311    }
312
313    /// Добавляет фильтр по странам с семантикой «хотя бы одна».
314    pub fn with_countries(mut self, values: impl IntoIterator<Item = impl Into<String>>) -> Self {
315        self.countries.extend(values.into_iter().map(Into::into));
316        self
317    }
318
319    /// Добавляет фильтр по жанрам КиноПоиска с семантикой «хотя бы один».
320    pub fn with_genres(mut self, values: impl IntoIterator<Item = impl Into<String>>) -> Self {
321        self.genres.extend(values.into_iter().map(Into::into));
322        self
323    }
324
325    fn encode_into(&self, output: &mut Parameters) {
326        output.push_joined("types", &self.types);
327        output.push_joined("year", &self.year);
328        output.push_joined("translation_id", &self.translation_ids);
329        output.push_joined("block_translations", &self.block_translations);
330        output.push_option("translation_type", self.translation_type);
331        output.push_joined("has_field", &self.has_field);
332        output.push_joined("has_field_and", &self.has_field_and);
333        output.push_bool("camrip", self.camrip);
334        output.push_bool("lgbt", self.lgbt);
335        output.push_joined("countries", &self.countries);
336        output.push_joined("countries_and", &self.countries_and);
337        output.push_joined("genres", &self.genres);
338        output.push_joined("genres_and", &self.genres_and);
339        output.push_joined("anime_genres", &self.anime_genres);
340        output.push_joined("anime_genres_and", &self.anime_genres_and);
341        output.push_joined("drama_genres", &self.drama_genres);
342        output.push_joined("drama_genres_and", &self.drama_genres_and);
343        output.push_joined("all_genres", &self.all_genres);
344        output.push_joined("all_genres_and", &self.all_genres_and);
345        output.push_string("duration", self.duration.as_deref());
346        output.push_string("kinopoisk_rating", self.kinopoisk_rating.as_deref());
347        output.push_string("imdb_rating", self.imdb_rating.as_deref());
348        output.push_string("shikimori_rating", self.shikimori_rating.as_deref());
349        output.push_string("mydramalist_rating", self.mydramalist_rating.as_deref());
350        output.push_joined("actors", &self.actors);
351        output.push_joined("actors_and", &self.actors_and);
352        output.push_joined("directors", &self.directors);
353        output.push_joined("directors_and", &self.directors_and);
354        output.push_joined("producers", &self.producers);
355        output.push_joined("producers_and", &self.producers_and);
356        output.push_joined("writers", &self.writers);
357        output.push_joined("writers_and", &self.writers_and);
358        output.push_joined("composers", &self.composers);
359        output.push_joined("composers_and", &self.composers_and);
360        output.push_joined("editors", &self.editors);
361        output.push_joined("editors_and", &self.editors_and);
362        output.push_joined("designers", &self.designers);
363        output.push_joined("designers_and", &self.designers_and);
364        output.push_joined("operators", &self.operators);
365        output.push_joined("operators_and", &self.operators_and);
366        output.push_joined("rating_mpaa", &self.rating_mpaa);
367        output.push_string("minimal_age", self.minimal_age.as_deref());
368        output.push_joined("anime_kind", &self.anime_kind);
369        output.push_joined("mydramalist_tags", &self.mydramalist_tags);
370        output.push_joined("mydramalist_tags_and", &self.mydramalist_tags_and);
371        output.push_joined("anime_status", &self.anime_status);
372        output.push_joined("drama_status", &self.drama_status);
373        output.push_joined("all_status", &self.all_status);
374        output.push_joined("anime_studios", &self.anime_studios);
375        output.push_joined("anime_studios_and", &self.anime_studios_and);
376        output.push_joined("anime_licensed_by", &self.anime_licensed_by);
377        output.push_joined("anime_licensed_by_and", &self.anime_licensed_by_and);
378    }
379}
380
381/// Запрос к `/years`.
382#[derive(Clone, Debug, Default, PartialEq, Eq)]
383pub struct YearsQuery {
384    pub filters: Filters,
385    pub sort: YearSort,
386}
387
388impl YearsQuery {
389    pub fn query_string(&self) -> String {
390        self.parameters().encoded()
391    }
392
393    fn parameters(&self) -> Parameters {
394        let mut parameters = Parameters::default();
395        self.filters.encode_into(&mut parameters);
396        parameters.push("sort", self.sort);
397        parameters
398    }
399}
400
401/// Запрос к `/genres`.
402#[derive(Clone, Debug, Default, PartialEq, Eq)]
403pub struct GenresQuery {
404    pub filters: Filters,
405    pub genres_type: GenreSource,
406    pub sort: LabelSort,
407}
408
409impl GenresQuery {
410    pub fn query_string(&self) -> String {
411        self.parameters().encoded()
412    }
413
414    fn parameters(&self) -> Parameters {
415        let mut parameters = Parameters::default();
416        self.filters.encode_into(&mut parameters);
417        parameters.push("genres_type", self.genres_type);
418        parameters.push("sort", self.sort);
419        parameters
420    }
421}
422
423/// Запрос к `/countries`.
424#[derive(Clone, Debug, Default, PartialEq, Eq)]
425pub struct CountriesQuery {
426    pub filters: Filters,
427    pub sort: LabelSort,
428}
429
430impl CountriesQuery {
431    pub fn query_string(&self) -> String {
432        self.parameters().encoded()
433    }
434
435    fn parameters(&self) -> Parameters {
436        let mut parameters = Parameters::default();
437        self.filters.encode_into(&mut parameters);
438        parameters.push("sort", self.sort);
439        parameters
440    }
441}
442
443/// Запрос к `/qualities/v2`.
444#[derive(Clone, Debug, Default, PartialEq, Eq)]
445pub struct QualitiesQuery {
446    pub filters: Filters,
447    pub sort: LabelSort,
448}
449
450impl QualitiesQuery {
451    pub fn query_string(&self) -> String {
452        self.parameters().encoded()
453    }
454
455    fn parameters(&self) -> Parameters {
456        let mut parameters = Parameters::default();
457        self.filters.encode_into(&mut parameters);
458        parameters.push("sort", self.sort);
459        parameters
460    }
461}
462
463/// Запрос к `/translations/v2`.
464#[derive(Clone, Debug, Default, PartialEq, Eq)]
465pub struct TranslationsQuery {
466    pub filters: Filters,
467    pub sort: LabelSort,
468}
469
470impl TranslationsQuery {
471    pub fn query_string(&self) -> String {
472        self.parameters().encoded()
473    }
474
475    fn parameters(&self) -> Parameters {
476        let mut parameters = Parameters::default();
477        self.filters.encode_into(&mut parameters);
478        parameters.push("sort", self.sort);
479        parameters
480    }
481}
482
483/// Запрос к `/list`.
484#[derive(Clone, Debug, Default, PartialEq, Eq)]
485pub struct ListQuery {
486    pub filters: Filters,
487    /// Количество результатов на странице, от 1 до 100. `None` передаёт выбор серверу.
488    pub limit: Option<u8>,
489    pub sort: ListSort,
490    pub order: SortOrder,
491    pub with_seasons: bool,
492    pub with_episodes: bool,
493    pub with_episodes_data: bool,
494    pub with_page_links: bool,
495    pub not_blocked_in: Vec<String>,
496    pub not_blocked_for_me: bool,
497    pub with_material_data: bool,
498    /// Курсор API из поля `next_page`; передавайте уже percent-decoded значение параметра `next`.
499    pub next: Option<String>,
500}
501
502impl ListQuery {
503    /// Проверяет границы `limit` до сетевого вызова.
504    pub fn validate(&self) -> Result<()> {
505        if self.limit.is_some_and(|limit| !(1..=100).contains(&limit)) {
506            return Err(Error::Validation("list limit must be in 1..=100".into()));
507        }
508        Ok(())
509    }
510
511    pub fn query_string(&self) -> Result<String> {
512        Ok(self.parameters()?.encoded())
513    }
514
515    fn parameters(&self) -> Result<Parameters> {
516        self.validate()?;
517        let mut parameters = Parameters::default();
518        self.filters.encode_into(&mut parameters);
519        if let Some(limit) = self.limit {
520            parameters.push("limit", limit);
521        }
522        parameters.push("sort", self.sort);
523        parameters.push("order", self.order);
524        parameters.push_bool_if_true("with_seasons", self.with_seasons);
525        parameters.push_bool_if_true("with_episodes", self.with_episodes);
526        parameters.push_bool_if_true("with_episodes_data", self.with_episodes_data);
527        parameters.push_bool_if_true("with_page_links", self.with_page_links);
528        parameters.push_joined("not_blocked_in", &self.not_blocked_in);
529        parameters.push_bool_if_true("not_blocked_for_me", self.not_blocked_for_me);
530        parameters.push_bool_if_true("with_material_data", self.with_material_data);
531        parameters.push_string("next", self.next.as_deref());
532        Ok(parameters)
533    }
534}
535
536/// Параметры точного и нечёткого поиска `/search`.
537///
538/// Хотя бы одно поле-критерий должно быть заполнено: название, Kodik ID, ссылка
539/// плеера или один из внешних идентификаторов.
540#[derive(Clone, Debug, Default, PartialEq, Eq)]
541pub struct SearchQuery {
542    pub title: Option<String>,
543    pub title_orig: Option<String>,
544    pub strict: bool,
545    pub full_match: bool,
546    pub id: Option<String>,
547    pub player_link: Option<String>,
548    pub kinopoisk_ids: Vec<String>,
549    pub imdb_ids: Vec<String>,
550    pub mdl_ids: Vec<String>,
551    pub worldart_animation_ids: Vec<String>,
552    pub worldart_cinema_ids: Vec<String>,
553    pub worldart_link: Option<String>,
554    pub shikimori_ids: Vec<String>,
555    /// Максимум результатов, от 1 до 100. `None` оставляет ограничение API.
556    pub limit: Option<u8>,
557    pub filters: Filters,
558    /// Последовательность ID/типов перевода с более высоким приоритетом. Значение `"0"`
559    /// в списке отключает серверную приоритизацию по умолчанию.
560    pub prioritize_translations: Vec<String>,
561    /// Последовательность ID/типов перевода с более низким приоритетом.
562    pub unprioritize_translations: Vec<String>,
563    pub prioritize_translation_type: Option<TranslationType>,
564    pub with_seasons: bool,
565    pub season: Option<u32>,
566    pub with_episodes: bool,
567    pub with_episodes_data: bool,
568    pub episode: Option<u32>,
569    pub with_page_links: bool,
570    pub not_blocked_in: Vec<String>,
571    pub not_blocked_for_me: bool,
572    pub with_material_data: bool,
573}
574
575impl SearchQuery {
576    /// Валидирует обязательный критерий поиска и зависимость `episode -> season`.
577    pub fn validate(&self) -> Result<()> {
578        if self.limit.is_some_and(|limit| !(1..=100).contains(&limit)) {
579            return Err(Error::Validation("search limit must be in 1..=100".into()));
580        }
581        if self.episode.is_some() && self.season.is_none() {
582            return Err(Error::Validation(
583                "search episode requires a corresponding season".into(),
584            ));
585        }
586        if !has_text(self.title.as_deref())
587            && !has_text(self.title_orig.as_deref())
588            && !has_text(self.id.as_deref())
589            && !has_text(self.player_link.as_deref())
590            && !has_non_blank_item(&self.kinopoisk_ids)
591            && !has_non_blank_item(&self.imdb_ids)
592            && !has_non_blank_item(&self.mdl_ids)
593            && !has_non_blank_item(&self.worldart_animation_ids)
594            && !has_non_blank_item(&self.worldart_cinema_ids)
595            && !has_text(self.worldart_link.as_deref())
596            && !has_non_blank_item(&self.shikimori_ids)
597        {
598            return Err(Error::Validation(
599                "search requires title, title_orig, Kodik ID, player link, or an external ID"
600                    .into(),
601            ));
602        }
603        Ok(())
604    }
605
606    pub fn query_string(&self) -> Result<String> {
607        Ok(self.parameters()?.encoded())
608    }
609
610    fn parameters(&self) -> Result<Parameters> {
611        self.validate()?;
612        let mut parameters = Parameters::default();
613        parameters.push_string("title", self.title.as_deref());
614        parameters.push_string("title_orig", self.title_orig.as_deref());
615        parameters.push_bool_if_true("strict", self.strict);
616        parameters.push_bool_if_true("full_match", self.full_match);
617        parameters.push_string("id", self.id.as_deref());
618        parameters.push_string("player_link", self.player_link.as_deref());
619        parameters.push_joined("kinopoisk_id", &self.kinopoisk_ids);
620        parameters.push_joined("imdb_id", &self.imdb_ids);
621        parameters.push_joined("mdl_id", &self.mdl_ids);
622        parameters.push_joined("worldart_animation_id", &self.worldart_animation_ids);
623        parameters.push_joined("worldart_cinema_id", &self.worldart_cinema_ids);
624        parameters.push_string("worldart_link", self.worldart_link.as_deref());
625        parameters.push_joined("shikimori_id", &self.shikimori_ids);
626        if let Some(limit) = self.limit {
627            parameters.push("limit", limit);
628        }
629        self.filters.encode_into(&mut parameters);
630        parameters.push_joined("prioritize_translations", &self.prioritize_translations);
631        parameters.push_joined("unprioritize_translations", &self.unprioritize_translations);
632        parameters.push_option(
633            "prioritize_translation_type",
634            self.prioritize_translation_type,
635        );
636        parameters.push_bool_if_true("with_seasons", self.with_seasons);
637        if let Some(season) = self.season {
638            parameters.push("season", season);
639        }
640        parameters.push_bool_if_true("with_episodes", self.with_episodes);
641        parameters.push_bool_if_true("with_episodes_data", self.with_episodes_data);
642        if let Some(episode) = self.episode {
643            parameters.push("episode", episode);
644        }
645        parameters.push_bool_if_true("with_page_links", self.with_page_links);
646        parameters.push_joined("not_blocked_in", &self.not_blocked_in);
647        parameters.push_bool_if_true("not_blocked_for_me", self.not_blocked_for_me);
648        parameters.push_bool_if_true("with_material_data", self.with_material_data);
649        Ok(parameters)
650    }
651}
652
653#[derive(Clone, Debug, Default)]
654pub(crate) struct Parameters(Vec<(String, String)>);
655
656impl Parameters {
657    pub(crate) fn push(&mut self, key: impl Into<String>, value: impl fmt::Display) {
658        self.0.push((key.into(), value.to_string()));
659    }
660
661    fn push_string(&mut self, key: impl Into<String>, value: Option<&str>) {
662        if let Some(value) = value.filter(|value| !value.trim().is_empty()) {
663            self.0.push((key.into(), value.to_owned()));
664        }
665    }
666
667    fn push_option<T: fmt::Display>(&mut self, key: impl Into<String>, value: Option<T>) {
668        if let Some(value) = value {
669            self.push(key, value);
670        }
671    }
672
673    fn push_bool(&mut self, key: impl Into<String>, value: Option<bool>) {
674        if let Some(value) = value {
675            self.push(key, value);
676        }
677    }
678
679    fn push_bool_if_true(&mut self, key: impl Into<String>, value: bool) {
680        if value {
681            self.push(key, "true");
682        }
683    }
684
685    fn push_joined<T: fmt::Display>(&mut self, key: impl Into<String>, values: &[T]) {
686        if !values.is_empty() {
687            let value = values
688                .iter()
689                .map(ToString::to_string)
690                .collect::<Vec<_>>()
691                .join(",");
692            self.0.push((key.into(), value));
693        }
694    }
695
696    pub(crate) fn extend(&mut self, other: Parameters) {
697        self.0.extend(other.0);
698    }
699
700    pub(crate) fn encoded(&self) -> String {
701        self.0
702            .iter()
703            .map(|(key, value)| format!("{}={}", percent_encode(key), percent_encode(value)))
704            .collect::<Vec<_>>()
705            .join("&")
706    }
707}
708
709pub(crate) trait IntoParameters {
710    fn into_parameters(self) -> Result<Parameters>;
711}
712
713impl IntoParameters for YearsQuery {
714    fn into_parameters(self) -> Result<Parameters> {
715        Ok(self.parameters())
716    }
717}
718
719impl IntoParameters for GenresQuery {
720    fn into_parameters(self) -> Result<Parameters> {
721        Ok(self.parameters())
722    }
723}
724
725impl IntoParameters for CountriesQuery {
726    fn into_parameters(self) -> Result<Parameters> {
727        Ok(self.parameters())
728    }
729}
730
731impl IntoParameters for QualitiesQuery {
732    fn into_parameters(self) -> Result<Parameters> {
733        Ok(self.parameters())
734    }
735}
736
737impl IntoParameters for TranslationsQuery {
738    fn into_parameters(self) -> Result<Parameters> {
739        Ok(self.parameters())
740    }
741}
742
743impl IntoParameters for ListQuery {
744    fn into_parameters(self) -> Result<Parameters> {
745        self.parameters()
746    }
747}
748
749impl IntoParameters for SearchQuery {
750    fn into_parameters(self) -> Result<Parameters> {
751        self.parameters()
752    }
753}
754
755fn has_text(value: Option<&str>) -> bool {
756    value.is_some_and(|value| !value.trim().is_empty())
757}
758
759fn has_non_blank_item(values: &[String]) -> bool {
760    values.iter().any(|value| !value.trim().is_empty())
761}
762
763fn percent_encode(value: &str) -> String {
764    let mut encoded = String::with_capacity(value.len());
765    for byte in value.bytes() {
766        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
767            encoded.push(byte as char);
768        } else {
769            encoded.push('%');
770            encoded.push(hex(byte >> 4));
771            encoded.push(hex(byte & 0x0f));
772        }
773    }
774    encoded
775}
776
777const fn hex(nibble: u8) -> char {
778    match nibble {
779        0..=9 => (b'0' + nibble) as char,
780        _ => (b'A' + nibble - 10) as char,
781    }
782}
783
784#[cfg(test)]
785mod tests {
786    use super::*;
787
788    #[test]
789    fn encodes_unicode_and_comma_separated_values() {
790        let query = YearsQuery {
791            filters: Filters::default()
792                .with_types([ContentType::AnimeSerial])
793                .with_countries(["США", "Россия"]),
794            sort: YearSort::Count,
795        };
796        assert_eq!(
797            query.query_string(),
798            "types=anime-serial&countries=%D0%A1%D0%A8%D0%90%2C%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D1%8F&sort=count"
799        );
800    }
801
802    #[test]
803    fn search_requires_a_criterion() {
804        let error = SearchQuery::default().validate().unwrap_err();
805        assert!(error.to_string().contains("search requires"));
806    }
807
808    #[test]
809    fn episode_requires_season() {
810        let query = SearchQuery {
811            title: Some("Test".into()),
812            episode: Some(4),
813            ..Default::default()
814        };
815        assert!(query.validate().is_err());
816    }
817
818    #[test]
819    fn search_rejects_empty_or_whitespace_only_criteria() {
820        for value in ["", "   ", "\n\t"] {
821            let query = SearchQuery {
822                title: Some(value.into()),
823                ..Default::default()
824            };
825            assert!(
826                query.validate().is_err(),
827                "criterion {value:?} must be rejected"
828            );
829        }
830
831        let query = SearchQuery {
832            kinopoisk_ids: vec![" ".into(), "\t".into()],
833            ..Default::default()
834        };
835        assert!(query.validate().is_err());
836    }
837
838    #[test]
839    fn list_and_search_reject_limits_outside_one_through_one_hundred() {
840        for limit in [0, 101] {
841            assert!(ListQuery {
842                limit: Some(limit),
843                ..Default::default()
844            }
845            .validate()
846            .is_err());
847
848            assert!(SearchQuery {
849                title: Some("Avatar".into()),
850                limit: Some(limit),
851                ..Default::default()
852            }
853            .validate()
854            .is_err());
855        }
856    }
857}