redseat-api 0.14.0

Rust client for Redseat media servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! What a library's grid shows: its order ([`Sorting`]) and its filters
//! ([`MediaFilter`]), as a user sets them, turned into a [`MediaQuery`] by
//! [`MediaFilter::query`], and the wording of their tokens ([`MediaFilter::tokens`]).
//! A search field offers people, tags and series as the user types ([`suggestions`],
//! matched by [`match_rank`] without case or accents).
//!
//! An app keeps these values and draws their controls; it never builds a query itself.
//! Ranges here are inclusive and in the user's units (megabytes, minutes, local days,
//! the rating scale). The server and the copy compare dates and durations strictly
//! (`<`, `>`), sizes and ratings inclusively (`<=`, `>=`), in bytes, seconds and
//! milliseconds: `query` gives each bound what they need, so a filter matches the same
//! medias in every app, offline or not.
//!
//! Days are the user's: the app gives where a local day starts in its time zone
//! (`day_start`), since a day's start depends on the zone and its daylight saving.

use serde::{Deserialize, Serialize};
use time::{Date, Month};

use crate::types::media::{FileType, MediaQuery, RsSort, SqlOrder};

/// What the grid is sorted by.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SortKey {
    /// When the photo or video was taken (`created`).
    #[default]
    Taken,
    /// When it was added to the library.
    Added,
    Name,
    Rating,
    Size,
}

impl SortKey {
    pub const ALL: [SortKey; 5] = [
        SortKey::Taken,
        SortKey::Added,
        SortKey::Name,
        SortKey::Rating,
        SortKey::Size,
    ];

    pub fn label(self) -> &'static str {
        match self {
            SortKey::Taken => "Date Taken",
            SortKey::Added => "Date Added",
            SortKey::Name => "Name",
            SortKey::Rating => "Rating",
            SortKey::Size => "Size",
        }
    }

    /// The direction a key starts in when chosen: newest, highest and largest first,
    /// names from A.
    pub fn natural_descending(self) -> bool {
        self != SortKey::Name
    }

    /// The two directions, as the key reads them: `(descending, ascending)`.
    pub fn direction_labels(self) -> (&'static str, &'static str) {
        match self {
            SortKey::Taken | SortKey::Added => ("Newest First", "Oldest First"),
            SortKey::Name => ("Z to A", "A to Z"),
            SortKey::Rating => ("Highest First", "Lowest First"),
            SortKey::Size => ("Largest First", "Smallest First"),
        }
    }

    /// The query's sort.
    pub fn rs_sort(self) -> RsSort {
        match self {
            SortKey::Taken => RsSort::Created,
            SortKey::Added => RsSort::Added,
            SortKey::Name => RsSort::Name,
            SortKey::Rating => RsSort::Rating,
            SortKey::Size => RsSort::Size,
        }
    }
}

/// The grid's order: newest taken first by default, like
/// [`grid_query`](crate::app::grid_query). Serialized in camelCase, for an app to keep.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Sorting {
    pub key: SortKey,
    pub descending: bool,
}

impl Default for Sorting {
    fn default() -> Self {
        Sorting {
            key: SortKey::Taken,
            descending: true,
        }
    }
}

impl Sorting {
    /// Sorted by `key`, in its natural direction.
    pub fn by(key: SortKey) -> Self {
        Sorting {
            key,
            descending: key.natural_descending(),
        }
    }

    /// The direction, as the key reads it ("Newest First").
    pub fn direction_label(self) -> &'static str {
        let (descending, ascending) = self.key.direction_labels();
        if self.descending {
            descending
        } else {
            ascending
        }
    }
}

/// Which kind of media shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum KindFilter {
    #[default]
    All,
    Photos,
    Videos,
    /// Neither photos nor videos: books, archives, other files.
    Other,
}

impl KindFilter {
    pub const ALL: [KindFilter; 4] = [
        KindFilter::All,
        KindFilter::Photos,
        KindFilter::Videos,
        KindFilter::Other,
    ];

    pub fn label(self) -> &'static str {
        match self {
            KindFilter::All => "All",
            KindFilter::Photos => "Photos",
            KindFilter::Videos => "Videos",
            KindFilter::Other => "Other",
        }
    }

    /// The query's types: none for all.
    pub fn types(self) -> Vec<FileType> {
        match self {
            KindFilter::All => Vec::new(),
            KindFilter::Photos => vec![FileType::Photo],
            KindFilter::Videos => vec![FileType::Video],
            KindFilter::Other => vec![
                FileType::Other,
                FileType::Archive,
                FileType::Album,
                FileType::Book,
                FileType::Directory,
            ],
        }
    }
}

/// A person, tag or series a media must be linked to.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Relation {
    Person(String),
    Tag(String),
    Serie(String),
}

/// A relation with its name, as its token reads it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamedRelation {
    pub relation: Relation,
    pub name: String,
}

/// Text as searches compare it: lower case, Latin letters without their accents
/// ("Élodie" reads "elodie"), so typing without accents finds names with them. An
/// accent written apart from its letter (decomposed Unicode, as macOS file names
/// have it) is a combining mark: dropped too.
pub fn fold(text: &str) -> String {
    text.chars()
        .filter(|c| !('\u{300}'..='\u{36f}').contains(c))
        .flat_map(char::to_lowercase)
        .map(|c| match c {
            'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' | 'ă' | 'ą' => 'a',
            'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => 'c',
            'ď' | 'đ' => 'd',
            'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e',
            'ĝ' | 'ğ' | 'ġ' | 'ģ' => 'g',
            'ì' | 'í' | 'î' | 'ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' | 'ı' => 'i',
            'ł' | 'ľ' | 'ĺ' | 'ļ' => 'l',
            'ñ' | 'ń' | 'ņ' | 'ň' => 'n',
            'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' | 'ŏ' | 'ő' => 'o',
            'ŕ' | 'ř' => 'r',
            'ś' | 'ŝ' | 'ş' | 'š' => 's',
            'ţ' | 'ť' => 't',
            'ù' | 'ú' | 'û' | 'ü' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => 'u',
            'ý' | 'ÿ' => 'y',
            'ź' | 'ż' | 'ž' => 'z',
            c => c,
        })
        .collect()
}

/// How well a name matches what was typed, folded both ([`fold`]): 0 when the name
/// starts with it, 1 when a word of it does, 2 when it is anywhere else; `None` when
/// it is not in the name or nothing was typed.
pub fn match_rank(name: &str, typed: &str) -> Option<u8> {
    let typed = fold(typed.trim());
    if typed.is_empty() {
        return None;
    }
    let name = fold(name);
    (name.match_indices(&typed))
        .map(|(at, _)| match name[..at].chars().next_back() {
            None => 0,
            Some(before) if !before.is_alphanumeric() => 1,
            Some(_) => 2,
        })
        .min()
}

/// What a search field offers for what was typed: the people, tags and series among
/// `choices` whose name matches ([`match_rank`]), `per_kind` of each at most, people
/// first, then tags, then series, the best match first in each (then by name). The
/// ones already `picked` are left out.
pub fn suggestions(
    typed: &str,
    choices: &[NamedRelation],
    picked: &[NamedRelation],
    per_kind: usize,
) -> Vec<NamedRelation> {
    let mut found: Vec<(&NamedRelation, u8, String)> = (choices.iter())
        .filter(|choice| !picked.iter().any(|p| p.relation == choice.relation))
        .filter_map(|choice| {
            let rank = match_rank(&choice.name, typed)?;
            Some((choice, rank, fold(&choice.name)))
        })
        .collect();
    let kind = |relation: &Relation| match relation {
        Relation::Person(_) => 0,
        Relation::Tag(_) => 1,
        Relation::Serie(_) => 2,
    };
    found.sort_by(|(a, rank_a, name_a), (b, rank_b, name_b)| {
        (kind(&a.relation), rank_a, name_a).cmp(&(kind(&b.relation), rank_b, name_b))
    });
    let mut taken = [0; 3];
    (found.into_iter())
        .filter(|(choice, _, _)| {
            let count = &mut taken[kind(&choice.relation)];
            *count += 1;
            *count <= per_kind
        })
        .map(|(choice, _, _)| choice.clone())
        .collect()
}

/// Local days, both included; either end may be open.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DayRange {
    pub from: Option<Date>,
    pub to: Option<Date>,
}

impl DayRange {
    pub fn is_set(&self) -> bool {
        self.from.is_some() || self.to.is_some()
    }

    /// The query's strict bounds in ms, `(after, before)`: from the first ms of `from`
    /// to the first ms after `to`.
    fn bounds(&self, day_start: &impl Fn(Date) -> Option<i64>) -> (Option<i64>, Option<i64>) {
        let after = self.from.and_then(day_start).map(|ms| ms - 1);
        let before = (self.to).and_then(Date::next_day).and_then(day_start);
        (after, before)
    }

    /// "12 Mar 2024 – 3 Apr 2024", "From 12 Mar 2024", "Until 3 Apr 2024".
    pub fn describe(&self) -> String {
        match (self.from, self.to) {
            (Some(from), Some(to)) if from == to => day_label(from),
            (Some(from), Some(to)) => format!("{} – {}", day_label(from), day_label(to)),
            (Some(from), None) => format!("From {}", day_label(from)),
            (None, Some(to)) => format!("Until {}", day_label(to)),
            (None, None) => String::new(),
        }
    }
}

/// "12 Mar 2024".
pub fn day_label(day: Date) -> String {
    format!("{} {} {}", day.day(), month_label(day.month()), day.year())
}

fn month_label(month: Month) -> &'static str {
    match month {
        Month::January => "Jan",
        Month::February => "Feb",
        Month::March => "Mar",
        Month::April => "Apr",
        Month::May => "May",
        Month::June => "Jun",
        Month::July => "Jul",
        Month::August => "Aug",
        Month::September => "Sep",
        Month::October => "Oct",
        Month::November => "Nov",
        Month::December => "Dec",
    }
}

/// Where a day starts in UTC, in ms: `day_start` for an app that shows UTC days.
pub fn utc_day_start(day: Date) -> Option<i64> {
    let seconds = day.midnight().assume_utc().unix_timestamp();
    seconds.checked_mul(1000)
}

/// Bounds of a number, both included; either may be open.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Bounds {
    pub min: Option<u64>,
    pub max: Option<u64>,
}

impl Bounds {
    pub fn is_set(&self) -> bool {
        self.min.is_some() || self.max.is_some()
    }

    /// "1–5 MB", "≥ 1 MB", "≤ 5 MB".
    pub fn describe(&self, unit: &str) -> String {
        match (self.min, self.max) {
            (Some(min), Some(max)) => format!("{min}–{max} {unit}"),
            (Some(min), None) => format!("≥ {min} {unit}"),
            (None, Some(max)) => format!("≤ {max} {unit}"),
            (None, None) => String::new(),
        }
    }
}

/// The rating scale of medias.
pub const MAX_RATING: u8 = 10;
/// The minimum tag confidence when a tag is picked and none is set, in percent. The
/// server and the copy apply none without one: `query` always gives it, so a control
/// can start at it.
pub const DEFAULT_TAG_CONFIDENCE: u16 = 50;

const MB: u64 = 1024 * 1024;

/// What narrows the grid. The default shows every media.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct MediaFilter {
    pub kind: KindFilter,
    /// Searched in names and descriptions.
    pub text: String,
    /// Each must match (tags include their child tags).
    pub relations: Vec<NamedRelation>,
    /// Minimum confidence of the tags matched, in percent; `None` for
    /// [`DEFAULT_TAG_CONFIDENCE`].
    /// Applies only with a tag.
    pub tag_confidence: Option<u16>,
    /// Ratings `min..=max` out of [`MAX_RATING`]; `None` for any, unrated included.
    pub rating: Option<(u8, u8)>,
    /// When taken (`created`).
    pub taken: DayRange,
    pub added: DayRange,
    /// In megabytes.
    pub size_mb: Bounds,
    /// In minutes.
    pub duration_min: Bounds,
}

/// One filter that is set, as its removable token says it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Token {
    Kind,
    Text,
    Relation(Relation),
    TagConfidence,
    Rating,
    Taken,
    Added,
    Size,
    Duration,
}

impl MediaFilter {
    /// Whether it shows every media: no token.
    pub fn is_empty(&self) -> bool {
        self.tokens().is_empty()
    }

    fn has_tags(&self) -> bool {
        (self.relations.iter()).any(|r| matches!(r.relation, Relation::Tag(_)))
    }

    /// The filters set, each with what its token reads, in the order tokens show.
    pub fn tokens(&self) -> Vec<(Token, String)> {
        let mut tokens = Vec::new();
        if self.kind != KindFilter::All {
            tokens.push((Token::Kind, self.kind.label().to_owned()));
        }
        let text = self.text.trim();
        if !text.is_empty() {
            tokens.push((Token::Text, format!("“{text}”")));
        }
        for named in &self.relations {
            tokens.push((Token::Relation(named.relation.clone()), named.name.clone()));
        }
        if let Some(confidence) = self.tag_confidence.filter(|_| self.has_tags()) {
            tokens.push((
                Token::TagConfidence,
                format!("Tag confidence ≥ {confidence}%"),
            ));
        }
        if let Some((min, max)) = self.rating {
            let text = match (min, max) {
                (min, MAX_RATING) => format!("Rating ≥ {min}"),
                (0, max) => format!("Rating ≤ {max}"),
                (min, max) if min == max => format!("Rating {min}"),
                (min, max) => format!("Rating {min}–{max}"),
            };
            tokens.push((Token::Rating, text));
        }
        if self.taken.is_set() {
            tokens.push((Token::Taken, format!("Taken: {}", self.taken.describe())));
        }
        if self.added.is_set() {
            tokens.push((Token::Added, format!("Added: {}", self.added.describe())));
        }
        if self.size_mb.is_set() {
            tokens.push((Token::Size, format!("Size {}", self.size_mb.describe("MB"))));
        }
        if self.duration_min.is_set() {
            tokens.push((
                Token::Duration,
                format!("Duration {}", self.duration_min.describe("min")),
            ));
        }
        tokens
    }

    /// Removes the filter a token shows.
    pub fn remove(&mut self, token: &Token) {
        match token {
            Token::Kind => self.kind = KindFilter::All,
            Token::Text => self.text.clear(),
            Token::Relation(relation) => self.relations.retain(|r| &r.relation != relation),
            Token::TagConfidence => self.tag_confidence = None,
            Token::Rating => self.rating = None,
            Token::Taken => self.taken = DayRange::default(),
            Token::Added => self.added = DayRange::default(),
            Token::Size => self.size_mb = Bounds::default(),
            Token::Duration => self.duration_min = Bounds::default(),
        }
    }

    /// The query of this filter in this order, for the copy
    /// ([`ServerCopy::medias`](crate::app::ServerCopy::medias)) or the server.
    /// `day_start` gives the first ms of a local day in the app's time zone
    /// ([`utc_day_start`] for UTC); a day it cannot place sets no bound.
    pub fn query(&self, sorting: Sorting, day_start: impl Fn(Date) -> Option<i64>) -> MediaQuery {
        let mut query = MediaQuery {
            sort: sorting.key.rs_sort(),
            order: if sorting.descending {
                SqlOrder::DESC
            } else {
                SqlOrder::ASC
            },
            types: self.kind.types(),
            ..Default::default()
        };
        let text = self.text.trim();
        if !text.is_empty() {
            query.text = Some(text.to_owned());
        }
        for named in &self.relations {
            match &named.relation {
                Relation::Person(id) => query.people.push(id.clone()),
                Relation::Tag(id) => query.tags.push(id.clone()),
                Relation::Serie(id) => query.series.push(id.clone()),
            }
        }
        if self.has_tags() {
            query.tags_confidence = Some(self.tag_confidence.unwrap_or(DEFAULT_TAG_CONFIDENCE));
        }
        // Ratings are compared inclusively.
        if let Some((min, max)) = self.rating {
            query.min_rating = Some(min.into());
            // The top of the scale sets no maximum: nothing is above it.
            query.max_rating = (max < MAX_RATING).then_some(max.into());
        }
        // Dates are compared strictly, in ms.
        (query.created_after, query.created_before) = self.taken.bounds(&day_start);
        (query.added_after, query.added_before) = self.added.bounds(&day_start);
        // Sizes are compared inclusively, in bytes: up to the last byte of the maximum.
        query.min_size = self.size_mb.min.map(|mb| mb.saturating_mul(MB));
        query.max_size =
            (self.size_mb.max).map(|mb| mb.saturating_add(1).saturating_mul(MB).saturating_sub(1));
        // Durations are compared strictly, in seconds.
        query.min_duration = (self.duration_min.min)
            .filter(|min| *min > 0)
            .map(|min| min.saturating_mul(60).saturating_sub(1));
        query.max_duration = (self.duration_min.max).map(|max| max.saturating_mul(60) + 1);
        query
    }
}

#[cfg(test)]
mod tests {
    use time::{Date, Month};

    use super::{
        Bounds, DEFAULT_TAG_CONFIDENCE, DayRange, KindFilter, MAX_RATING, MediaFilter,
        NamedRelation, Relation, SortKey, Sorting, Token, fold, match_rank, suggestions,
        utc_day_start,
    };
    use crate::types::media::{FileType, RsSort, SqlOrder};

    fn named(relation: Relation, name: &str) -> NamedRelation {
        NamedRelation {
            relation,
            name: name.to_owned(),
        }
    }

    fn march(day: u8) -> Date {
        Date::from_calendar_date(2024, Month::March, day).unwrap()
    }

    #[cfg(feature = "mirror")]
    #[test]
    fn the_default_is_the_grid_query() {
        let query = MediaFilter::default().query(Sorting::default(), utc_day_start);
        let grid = crate::app::grid_query();
        assert_eq!((query.sort, query.order), (grid.sort, grid.order));
        assert!(query.types.is_empty() && query.text.is_none());
        assert!(MediaFilter::default().is_empty());
    }

    #[test]
    fn each_key_starts_in_its_natural_direction() {
        assert!(Sorting::by(SortKey::Taken).descending);
        assert!(!Sorting::by(SortKey::Name).descending);
        assert_eq!(Sorting::by(SortKey::Name).direction_label(), "A to Z");
        let query = MediaFilter::default().query(Sorting::by(SortKey::Size), utc_day_start);
        assert_eq!((query.sort, query.order), (RsSort::Size, SqlOrder::DESC));
    }

    #[test]
    fn sorting_keeps_its_serialized_form() {
        let json = serde_json::to_string(&Sorting::by(SortKey::Added)).unwrap();
        assert_eq!(json, r#"{"key":"added","descending":true}"#);
        let read: Sorting = serde_json::from_str(r#"{"key":"name"}"#).unwrap();
        assert_eq!(read.key, SortKey::Name);
    }

    #[test]
    fn relations_go_to_their_lists() {
        let filter = MediaFilter {
            relations: vec![
                named(Relation::Person("p1".into()), "Alice"),
                named(Relation::Tag("t1".into()), "Beach"),
                named(Relation::Serie("s1".into()), "Show"),
            ],
            tag_confidence: Some(80),
            ..Default::default()
        };
        let query = filter.query(Sorting::default(), utc_day_start);
        assert_eq!(query.people, ["p1"]);
        assert_eq!(query.tags, ["t1"]);
        assert_eq!(query.series, ["s1"]);
        assert_eq!(query.tags_confidence, Some(80));
    }

    #[test]
    fn tag_confidence_needs_a_tag() {
        let filter = MediaFilter {
            tag_confidence: Some(80),
            ..Default::default()
        };
        let query = filter.query(Sorting::default(), utc_day_start);
        assert_eq!(query.tags_confidence, None);
        assert!(filter.is_empty());
    }

    #[test]
    fn a_tag_without_a_confidence_takes_the_default() {
        let filter = MediaFilter {
            relations: vec![named(Relation::Tag("t1".into()), "Beach")],
            ..Default::default()
        };
        let query = filter.query(Sorting::default(), utc_day_start);
        assert_eq!(query.tags_confidence, Some(DEFAULT_TAG_CONFIDENCE));
        // The default needs no token.
        assert_eq!(filter.tokens().len(), 1);
    }

    #[test]
    fn kinds_and_text() {
        let filter = MediaFilter {
            kind: KindFilter::Videos,
            text: "  beach ".into(),
            ..Default::default()
        };
        let query = filter.query(Sorting::default(), utc_day_start);
        assert_eq!(query.types, [FileType::Video]);
        assert_eq!(query.text.as_deref(), Some("beach"));
        let blank = MediaFilter {
            text: "   ".into(),
            ..Default::default()
        };
        assert!(blank.is_empty());
    }

    #[test]
    fn rating_at_the_top_sets_no_maximum() {
        let filter = MediaFilter {
            rating: Some((7, MAX_RATING)),
            ..Default::default()
        };
        let query = filter.query(Sorting::default(), utc_day_start);
        assert_eq!((query.min_rating, query.max_rating), (Some(7.), None));
        assert_eq!(filter.tokens()[0].1, "Rating ≥ 7");
    }

    #[test]
    fn days_include_both_ends_in_the_apps_zone() {
        let range = DayRange {
            from: Some(march(12)),
            to: Some(march(14)),
        };
        assert_eq!(range.describe(), "12 Mar 2024 – 14 Mar 2024");
        let filter = MediaFilter {
            taken: range,
            ..Default::default()
        };
        let query = filter.query(Sorting::default(), utc_day_start);
        // 2024-03-12T00:00:00Z and 2024-03-15T00:00:00Z.
        let (start, end) = (1_710_201_600_000, 1_710_460_800_000);
        assert_eq!(query.created_after, Some(start - 1));
        assert_eq!(query.created_before, Some(end));
        // A day starting an hour earlier, as in UTC+1.
        let hour = 3_600_000;
        let query = filter.query(Sorting::default(), |day| {
            utc_day_start(day).map(|ms| ms - hour)
        });
        assert_eq!(query.created_after, Some(start - hour - 1));
        assert_eq!(query.created_before, Some(end - hour));
    }

    #[test]
    fn sizes_and_durations_include_their_bounds() {
        let filter = MediaFilter {
            size_mb: Bounds {
                min: Some(1),
                max: Some(2),
            },
            duration_min: Bounds {
                min: Some(1),
                max: Some(2),
            },
            ..Default::default()
        };
        let query = filter.query(Sorting::default(), utc_day_start);
        assert_eq!(query.min_size, Some(1024 * 1024));
        assert_eq!(query.max_size, Some(3 * 1024 * 1024 - 1));
        // Strict, so that 60 s and 120 s match.
        assert_eq!(
            (query.min_duration, query.max_duration),
            (Some(59), Some(121))
        );
        assert_eq!(filter.tokens()[0].1, "Size 1–2 MB");
    }

    #[test]
    fn names_match_without_case_or_accents() {
        assert_eq!(fold("Élodie ÇA Ñu"), "elodie ca nu");
        // The name's start, a word's start, elsewhere.
        assert_eq!(match_rank("Arnaud", "arn"), Some(0));
        assert_eq!(match_rank("Jean-Arnaud", "arn"), Some(1));
        assert_eq!(match_rank("Bernard", "rna"), Some(2));
        assert_eq!(match_rank("Ma Arnaud", "  ARN "), Some(1));
        assert_eq!(match_rank("Hélène", "helene"), Some(0));
        // Decomposed: the accent apart from its letter.
        assert_eq!(fold("Ame\u{301}lie"), "amelie");
        assert_eq!(match_rank("Ame\u{301}lie", "Amélie"), Some(0));
        assert_eq!(match_rank("Arnaud", "bob"), None);
        assert_eq!(match_rank("Arnaud", "  "), None);
    }

    #[test]
    fn suggestions_go_by_kind_then_match() {
        let choices = [
            named(Relation::Serie("s1".into()), "Arnold's trip"),
            named(Relation::Tag("t1".into()), "Barnyard"),
            named(Relation::Person("p1".into()), "Barnabé"),
            named(Relation::Person("p2".into()), "Jean Arnaud"),
            named(Relation::Person("p3".into()), "Arnaud"),
            named(Relation::Person("p4".into()), "Alice"),
            named(Relation::Tag("t2".into()), "Arnhem"),
        ];
        let names = |found: Vec<NamedRelation>| -> Vec<String> {
            found.into_iter().map(|n| n.name).collect()
        };
        assert_eq!(
            names(suggestions("arn", &choices, &[], 5)),
            [
                "Arnaud",
                "Jean Arnaud",
                "Barnabé",
                "Arnhem",
                "Barnyard",
                "Arnold's trip"
            ]
        );
        // At most two of each kind, without the ones picked.
        let picked = [named(Relation::Person("p3".into()), "Arnaud")];
        assert_eq!(
            names(suggestions("arn", &choices, &picked, 2)),
            [
                "Jean Arnaud",
                "Barnabé",
                "Arnhem",
                "Barnyard",
                "Arnold's trip"
            ]
        );
        assert!(suggestions("", &choices, &[], 5).is_empty());
    }

    #[test]
    fn a_token_removes_its_filter() {
        let mut filter = MediaFilter {
            kind: KindFilter::Photos,
            relations: vec![
                named(Relation::Person("p1".into()), "Alice"),
                named(Relation::Tag("t1".into()), "Beach"),
            ],
            ..Default::default()
        };
        let tokens: Vec<Token> = filter.tokens().into_iter().map(|(t, _)| t).collect();
        assert_eq!(tokens.len(), 3);
        filter.remove(&Token::Relation(Relation::Person("p1".into())));
        filter.remove(&Token::Kind);
        assert_eq!(filter.relations.len(), 1);
        assert_eq!(filter.kind, KindFilter::All);
    }
}