redseat-api 0.18.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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
//! A media's details panel, as the web app's `ZoomBoxDetail.svelte` shows it: its
//! name, rating, description, dates, info rows, place and origin, its relations as
//! chips (people, series, movie, book, tags), what the "Add" field offers, its faces,
//! and what the user may change. Plus what a viewer needs to know about a media before
//! reading its file.
//!
//! The changes the panel makes go through the copy's action queue (offline too):
//! [`add_action`], [`remove_action`] and [`paste_tags_action`] give the [`Action`] of a
//! relation chip, and the panel builds the others itself (`MediaRename`,
//! `MediaDescription`, `MediaCreated`, `MediaLocation`, `MediaRating`...). Faces, the
//! "AI tag", a refresh and image uploads are calls on the server
//! ([`crate::LibraryApi`]).

use std::collections::HashMap;

use crate::library::MediaItem;
#[cfg(feature = "mirror")]
use crate::mirror::Action;
use crate::types::book::Book;
use crate::types::library::{LibraryRole, ServerLibraryForRead};
use crate::types::media::{FaceEmbedding, FileType, Media};
#[cfg(feature = "mirror")]
use crate::types::media::{FileEpisode, MediaItemReference};
use crate::types::movie::Movie;
use crate::types::person::Person;
use crate::types::serie::Serie;
use crate::types::tag::Tag;
use rs_plugin_common_interfaces::url::RsLink;

use super::filter::{Candidate, Found, best, fold, words_rank};
use super::text;

/// A library's items of one kind, sorted by name (without case or accents), with an
/// index by id.
#[derive(Debug, Clone, PartialEq)]
struct Items<T> {
    list: Vec<T>,
    index: HashMap<String, usize>,
}

impl<T> Default for Items<T> {
    fn default() -> Self {
        Items {
            list: Vec::new(),
            index: HashMap::new(),
        }
    }
}

impl<T> Items<T> {
    fn new(mut list: Vec<T>, id: fn(&T) -> &str, name: fn(&T) -> &str) -> Self {
        list.sort_by_cached_key(|item| {
            (fold(name(item)), name(item).to_owned(), id(item).to_owned())
        });
        let index = (list.iter().enumerate())
            .map(|(at, item)| (id(item).to_owned(), at))
            .collect();
        Items { list, index }
    }

    fn get(&self, id: &str) -> Option<&T> {
        self.index.get(id).and_then(|at| self.list.get(*at))
    }
}

/// Names of a library's items by id (decrypted by `ServerCopy::names`): medias name
/// them by id only. Keeps the items whole, for their images (`posterv`).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Names {
    people: Items<Person>,
    tags: Items<Tag>,
    series: Items<Serie>,
    movies: Items<Movie>,
    books: Items<Book>,
}

impl Names {
    pub fn new(
        people: Vec<Person>,
        tags: Vec<Tag>,
        series: Vec<Serie>,
        movies: Vec<Movie>,
        books: Vec<Book>,
    ) -> Self {
        Names {
            people: Items::new(people, |p| &p.id, |p| &p.name),
            tags: Items::new(tags, |t| &t.id, |t| &t.name),
            series: Items::new(series, |s| &s.id, |s| &s.name),
            movies: Items::new(movies, |m| &m.id, |m| &m.name),
            books: Items::new(books, |b| &b.id, |b| &b.name),
        }
    }

    pub fn person(&self, id: &str) -> Option<&str> {
        self.people.get(id).map(|p| p.name.as_str())
    }

    pub fn tag(&self, id: &str) -> Option<&str> {
        self.tags.get(id).map(|t| t.name.as_str())
    }

    pub fn serie(&self, id: &str) -> Option<&str> {
        self.series.get(id).map(|s| s.name.as_str())
    }

    pub fn movie(&self, id: &str) -> Option<&str> {
        self.movies.get(id).map(|m| m.name.as_str())
    }

    pub fn book(&self, id: &str) -> Option<&str> {
        self.books.get(id).map(|b| b.name.as_str())
    }

    /// The name of an item of `kind`.
    pub fn name(&self, kind: RelationKind, id: &str) -> Option<&str> {
        match kind {
            RelationKind::Person => self.person(id),
            RelationKind::Tag => self.tag(id),
            RelationKind::Serie => self.serie(id),
            RelationKind::Movie => self.movie(id),
            RelationKind::Book => self.book(id),
        }
    }

    pub fn person_item(&self, id: &str) -> Option<&Person> {
        self.people.get(id)
    }

    pub fn tag_item(&self, id: &str) -> Option<&Tag> {
        self.tags.get(id)
    }

    pub fn serie_item(&self, id: &str) -> Option<&Serie> {
        self.series.get(id)
    }

    pub fn movie_item(&self, id: &str) -> Option<&Movie> {
        self.movies.get(id)
    }

    pub fn book_item(&self, id: &str) -> Option<&Book> {
        self.books.get(id)
    }

    /// The library's people, by name.
    pub fn people(&self) -> impl Iterator<Item = &Person> {
        self.people.list.iter()
    }

    /// What a person picker offers for `typed` (assigning a face): the people whose
    /// name matches, ranked like [`add_choices`], `limit` at most. Nothing typed: the
    /// first `limit` people by name.
    pub fn person_choices(&self, typed: &str, limit: usize) -> Vec<AddChoice> {
        let people = (self.people.list.iter())
            .map(|p| (p.id.as_str(), Candidate::new(&p.name, p.alt.as_ref())));
        if typed.trim().is_empty() {
            return (people.take(limit))
                .map(|(id, p)| choice(RelationKind::Person, id, p.name, None))
                .collect();
        }
        ranked(RelationKind::Person, people, typed, limit)
    }

    /// The names of every item of `kind`.
    fn names_of(&self, kind: RelationKind) -> Vec<&str> {
        fn names<T>(items: &Items<T>, name: fn(&T) -> &str) -> Vec<&str> {
            items.list.iter().map(name).collect()
        }
        match kind {
            RelationKind::Person => names(&self.people, |p| &p.name),
            RelationKind::Tag => names(&self.tags, |t| &t.name),
            RelationKind::Serie => names(&self.series, |s| &s.name),
            RelationKind::Movie => names(&self.movies, |m| &m.name),
            RelationKind::Book => names(&self.books, |b| &b.name),
        }
    }
}

/// One row of the details: a label and its value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Detail {
    pub label: &'static str,
    pub value: String,
}

/// What a media is linked to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RelationKind {
    Person,
    Tag,
    Serie,
    Movie,
    Book,
}

impl RelationKind {
    /// Every kind, in the order the "Add" field lists them.
    pub const ALL: [RelationKind; 5] = [
        RelationKind::Person,
        RelationKind::Tag,
        RelationKind::Serie,
        RelationKind::Movie,
        RelationKind::Book,
    ];

    /// What one is called: "person", "tag", "series", "movie", "book".
    pub fn name(self) -> &'static str {
        match self {
            RelationKind::Person => "person",
            RelationKind::Tag => "tag",
            RelationKind::Serie => "series",
            RelationKind::Movie => "movie",
            RelationKind::Book => "book",
        }
    }
}

/// A relation of the media, as a chip shows it.
#[derive(Debug, Clone, PartialEq)]
pub struct Chip {
    pub kind: RelationKind,
    pub id: String,
    /// The id when the name is unknown (as the web app).
    pub name: String,
    /// A series' episode ("S1 · E2", "Season 1", "Episode 2"), a tag's confidence and
    /// path ("85% · /animals").
    pub detail: Option<String>,
    /// Series only: kept to remove the right entry.
    pub season: Option<u32>,
    pub episode: Option<u32>,
}

impl Chip {
    fn new(names: &Names, kind: RelationKind, id: &str, detail: Option<String>) -> Self {
        Chip {
            kind,
            id: id.to_owned(),
            name: names.name(kind, id).unwrap_or(id).to_owned(),
            detail,
            season: None,
            episode: None,
        }
    }
}

/// A tag of the media.
#[derive(Debug, Clone, PartialEq)]
pub struct TagChip {
    pub chip: Chip,
    /// How sure the server's model is, in percent; `None` when the user set it.
    pub confidence: Option<u16>,
    /// Below 100 %: the user may validate it (add it again, without a confidence).
    pub to_validate: bool,
    /// A tag the server's model made.
    pub generated: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateKind {
    /// When it was made (a photo taken): `Media::created`.
    Taken,
    Added,
    Modified,
}

/// A date of the media, in Unix ms: the app writes it in the user's time zone.
#[derive(Debug, Clone, PartialEq)]
pub struct DateRow {
    pub kind: DateKind,
    /// "Taken", "Added", "Modified".
    pub label: &'static str,
    pub ms: i64,
}

/// Where a media was made.
#[derive(Debug, Clone, PartialEq)]
pub struct Place {
    pub lat: f64,
    pub long: f64,
    /// "48.85660, 2.35220".
    pub label: String,
    /// An OpenStreetMap page centred on it ([`map_url`]).
    pub map_url: String,
}

/// Where a media came from (`Media::origin`).
#[derive(Debug, Clone, PartialEq)]
pub struct Origin {
    /// The platform, or a link's host ("twitter", "example.com"), as the web app's
    /// `linkString`.
    pub label: String,
    /// A link's address, when the origin is one. Other platforms' need the server's
    /// plugins to make one.
    pub url: Option<String>,
}

/// What the user may do with a media (the web app's role checks, `hasRolesAccess`:
/// admin includes write, write includes read).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Access {
    /// Change it: the write role, or the user uploaded it.
    pub edit: bool,
    /// Delete it: the admin role, or the user uploaded it.
    pub delete: bool,
    /// The admin role: detect its faces again.
    pub admin: bool,
}

/// What `user` (their id, `None` when unknown) may do with `media` in `library`. A
/// library without roles is the server admin's view (the server sends no roles to its
/// admin, who may do everything).
pub fn access(library: &ServerLibraryForRead, media: &Media, user: Option<&str>) -> Access {
    let (admin, write) = match &library.roles {
        None => (true, true),
        Some(roles) => (
            roles.contains(&LibraryRole::Admin),
            (roles.iter()).any(|r| matches!(r, LibraryRole::Admin | LibraryRole::Write)),
        ),
    };
    let uploader = user.is_some_and(|user| media.uploader.as_deref() == Some(user));
    Access {
        edit: write || uploader,
        delete: admin || uploader,
        admin,
    }
}

/// A media as its details panel shows it.
#[derive(Debug, Clone, PartialEq)]
pub struct MediaDetails {
    pub id: String,
    pub kind: FileType,
    pub name: String,
    /// `None` when empty.
    pub description: Option<String>,
    /// 1 to 10; `None` when not rated.
    pub rating: Option<u8>,
    /// Taken, Added, Modified: those set.
    pub dates: Vec<DateRow>,
    /// Type, Size, Dimensions, Duration, Pages, Camera, Exposure, Video, Color profile,
    /// Uploader: those set.
    pub info: Vec<Detail>,
    pub place: Option<Place>,
    pub origin: Option<Origin>,
    /// The media it was made from (`Media::original_id`).
    pub original: Option<String>,
    pub pages: Option<usize>,
    pub people: Vec<Chip>,
    pub series: Vec<Chip>,
    pub movie: Option<Chip>,
    pub book: Option<Chip>,
    /// The tags the user set (not generated), by confidence (none first, as 100 %+),
    /// then name.
    pub tags: Vec<TagChip>,
    /// The tags the server's model made, sorted alike.
    pub generated_tags: Vec<TagChip>,
}

impl MediaDetails {
    pub fn new(media: &MediaItem, names: &Names) -> Self {
        let item = &media.item;
        let relations = media.relations.as_ref();
        let dates = [
            (DateKind::Taken, "Taken", item.created),
            (DateKind::Added, "Added", item.added),
            (DateKind::Modified, "Modified", item.modified),
        ]
        .into_iter()
        .filter_map(|(kind, label, ms)| {
            Some(DateRow {
                kind,
                label,
                ms: ms?,
            })
        })
        .collect();
        let place = match (item.lat, item.long, map_url(item)) {
            (Some(lat), Some(long), Some(map_url)) => Some(Place {
                lat,
                long,
                label: format!("{lat:.5}, {long:.5}"),
                map_url,
            }),
            _ => None,
        };
        let people = (relations
            .and_then(|r| r.people.as_ref())
            .into_iter()
            .flatten())
        .map(|p| Chip::new(names, RelationKind::Person, &p.id, None))
        .collect();
        let series = (relations
            .and_then(|r| r.series.as_ref())
            .into_iter()
            .flatten())
        .map(|s| Chip {
            season: s.season,
            episode: s.episode,
            ..Chip::new(
                names,
                RelationKind::Serie,
                &s.id,
                episode_label(s.season, s.episode, s.episode_to),
            )
        })
        .collect();
        let first = |list: Option<&Vec<String>>| {
            list.and_then(|l| l.iter().find(|id| !id.is_empty()).cloned())
        };
        let movie = first(relations.and_then(|r| r.movies.as_ref()))
            .map(|id| Chip::new(names, RelationKind::Movie, &id, None));
        let book = first(relations.and_then(|r| r.books.as_ref()))
            .map(|id| Chip::new(names, RelationKind::Book, &id, None));
        let mut tags: Vec<TagChip> = (relations.and_then(|r| r.tags.as_ref()).into_iter())
            .flatten()
            .map(|reference| {
                let tag = names.tag_item(&reference.id);
                let path = tag.map(|t| t.path.as_str());
                TagChip {
                    chip: Chip::new(
                        names,
                        RelationKind::Tag,
                        &reference.id,
                        tag_label(reference.conf, path),
                    ),
                    confidence: reference.conf,
                    to_validate: reference.conf.is_some_and(|c| c < 100),
                    generated: tag.is_some_and(|t| t.generated),
                }
            })
            .collect();
        tags.sort_by_cached_key(|t| {
            let confidence = t.confidence.unwrap_or(101);
            (
                std::cmp::Reverse(confidence),
                fold(&t.chip.name),
                t.chip.name.clone(),
            )
        });
        let (generated_tags, tags) = tags.into_iter().partition(|t| t.generated);
        MediaDetails {
            id: item.id.clone(),
            kind: item.kind.clone(),
            name: item.name.clone(),
            description: (item.description.clone()).filter(|d| !d.trim().is_empty()),
            rating: (item.rating.map(f32::round))
                .filter(|r| (1.0..=10.0).contains(r))
                .map(|r| r as u8),
            dates,
            info: info(item),
            place,
            origin: item.origin.as_ref().map(origin),
            original: item.original_id.clone().filter(|id| !id.is_empty()),
            pages: item.pages.filter(|p| *p > 0),
            people,
            series,
            movie,
            book,
            tags,
            generated_tags,
        }
    }
}

/// A series entry's episode: "S1 · E2" ("S1 · E2–E4" for several), "Season 1",
/// "Episode 2".
fn episode_label(season: Option<u32>, episode: Option<u32>, to: Option<u32>) -> Option<String> {
    let episode = episode.map(|e| match to.filter(|to| *to > e) {
        Some(to) => (format!("E{e}–E{to}"), format!("Episodes {e}–{to}")),
        None => (format!("E{e}"), format!("Episode {e}")),
    });
    match (season, episode) {
        (Some(season), Some((short, _))) => Some(format!("S{season} · {short}")),
        (Some(season), None) => Some(format!("Season {season}")),
        (None, Some((_, long))) => Some(long),
        (None, None) => None,
    }
}

/// A tag's confidence then path: "85% · /animals" (the web app's `tagDescription`). The
/// root path ("/") says nothing and is left out.
fn tag_label(confidence: Option<u16>, path: Option<&str>) -> Option<String> {
    let parts: Vec<String> = [
        confidence.map(|c| format!("{c}%")),
        path.filter(|p| !p.is_empty() && *p != "/")
            .map(str::to_owned),
    ]
    .into_iter()
    .flatten()
    .collect();
    (!parts.is_empty()).then(|| parts.join(" · "))
}

/// The web app's `linkString`: a link's host (without `www.`), else its platform.
fn origin(link: &RsLink) -> Origin {
    let id = link.id.trim();
    if link.platform != "link" || id.is_empty() {
        return Origin {
            label: link.platform.clone(),
            url: None,
        };
    }
    match url::Url::parse(id) {
        Ok(url) => Origin {
            label: (url.host_str())
                .map(|host| host.trim_start_matches("www.").to_owned())
                .unwrap_or_else(|| id.to_owned()),
            url: matches!(url.scheme(), "http" | "https").then(|| id.to_owned()),
        },
        Err(_) => Origin {
            label: id.to_owned(),
            url: None,
        },
    }
}

/// The info rows: only those the media has a value for.
fn info(item: &Media) -> Vec<Detail> {
    let mut rows = Vec::new();
    let mut push = |label: &'static str, value: Option<String>| {
        if let Some(value) = value.filter(|v| !v.trim().is_empty()) {
            rows.push(Detail { label, value });
        }
    };
    let video = is_video(item);
    push("Type", Some(item.mimetype.clone()));
    push("Size", item.size.map(text::bytes));
    push("Dimensions", dimensions(item));
    push(
        "Duration",
        (item.duration)
            .filter(|d| *d > 0 && video)
            .map(|d| text::duration(d as u64)),
    );
    push(
        "Pages",
        item.pages.filter(|p| *p > 0).map(|p| p.to_string()),
    );
    push("Camera", item.model.clone());
    if item.kind == FileType::Photo {
        let shutter = item.sspeed.as_deref();
        push(
            "Exposure",
            text::exposure(item.focal, item.f_number, shutter, item.iso),
        );
    }
    if video {
        push("Video", video_line(item));
    }
    push("Color profile", item.icc.clone());
    push("Uploader", item.uploader.clone());
    rows
}

/// "29.97 fps · H.264, AAC · 12.4 Mb/s": the parts the media has.
fn video_line(item: &Media) -> Option<String> {
    let codecs: Vec<String> = (item.vcodecs.iter().flatten())
        .filter(|c| !c.trim().is_empty())
        .map(|c| text::video_codec(c))
        .chain((item.acodecs.iter().flatten()).filter_map(|c| super::tracks::codec_name(c)))
        .collect();
    let parts: Vec<String> = [
        (item.fps)
            .filter(|f| f.is_finite() && *f > 0.)
            .map(|f| format!("{} fps", text::decimals(f, 2))),
        (!codecs.is_empty()).then(|| codecs.join(", ")),
        item.bitrate.filter(|b| *b > 0).map(text::bitrate),
    ]
    .into_iter()
    .flatten()
    .collect();
    (!parts.is_empty()).then(|| parts.join(" · "))
}

/// One choice of the "Add" field.
#[derive(Debug, Clone, PartialEq)]
pub struct AddChoice {
    pub kind: RelationKind,
    pub id: String,
    pub name: String,
    /// A tag's path.
    pub detail: Option<String>,
}

fn choice(kind: RelationKind, id: &str, name: &str, detail: Option<String>) -> AddChoice {
    AddChoice {
        kind,
        id: id.to_owned(),
        name: name.to_owned(),
        detail,
    }
}

/// The items that the words of `typed` find ([`words_rank`]), the best first, then by
/// name, `limit` at most.
fn ranked<'a>(
    kind: RelationKind,
    items: impl Iterator<Item = (&'a str, Candidate<'a>)>,
    typed: &str,
    limit: usize,
) -> Vec<AddChoice> {
    let words: Vec<&str> = typed.split_whitespace().collect();
    let found = items
        .filter_map(|(id, candidate)| {
            let rank = words_rank(&words, &candidate)?;
            let detail = (candidate.path)
                .filter(|p| !p.is_empty() && *p != "/")
                .map(str::to_owned);
            let item = choice(kind, id, candidate.name, detail);
            Some(Found::new(&candidate, rank, item))
        })
        .collect();
    best(found, limit)
}

/// What the "Add" field offers for `typed` (the web app's `DetailAutocomplete`): the
/// people, tags, series, movies and books that the words typed find ([`words_rank`]:
/// each in a name or another name, or a tag's path, without case or accents: "cloth
/// sk" finds the tag "skirt" in "/cloth"), `per_kind` of each, in that kind order
/// ([`best`]: the best first, tags then by their full path). What
/// the media has is left out, except its tags below 100 % (adding one validates it).
/// Generated tags only with `generated` (the generated tags shown). Nothing typed:
/// nothing.
pub fn add_choices(
    typed: &str,
    names: &Names,
    media: &MediaItem,
    generated: bool,
    per_kind: usize,
) -> Vec<AddChoice> {
    if typed.trim().is_empty() || per_kind == 0 {
        return Vec::new();
    }
    let relations = media.relations.as_ref();
    let people: Vec<&str> = (relations
        .and_then(|r| r.people.as_ref())
        .into_iter()
        .flatten())
    .map(|p| p.id.as_str())
    .collect();
    let tags: Vec<&str> = (relations
        .and_then(|r| r.tags.as_ref())
        .into_iter()
        .flatten())
    .filter(|t| t.conf.is_none_or(|c| c >= 100))
    .map(|t| t.id.as_str())
    .collect();
    let series: Vec<&str> = (relations
        .and_then(|r| r.series.as_ref())
        .into_iter()
        .flatten())
    .map(|s| s.id.as_str())
    .collect();
    let listed = |list: Option<&Vec<String>>| -> Vec<String> { list.cloned().unwrap_or_default() };
    let movies = listed(relations.and_then(|r| r.movies.as_ref()));
    let books = listed(relations.and_then(|r| r.books.as_ref()));

    let mut choices = Vec::new();
    choices.extend(ranked(
        RelationKind::Person,
        (names.people.list.iter())
            .filter(|p| !people.contains(&p.id.as_str()))
            .map(|p| (p.id.as_str(), Candidate::new(&p.name, p.alt.as_ref()))),
        typed,
        per_kind,
    ));
    choices.extend(ranked(
        RelationKind::Tag,
        (names.tags.list.iter())
            .filter(|t| (generated || !t.generated) && !tags.contains(&t.id.as_str()))
            .map(|t| {
                let candidate = Candidate {
                    path: Some(&t.path),
                    ..Candidate::new(&t.name, t.alt.as_ref())
                };
                (t.id.as_str(), candidate)
            }),
        typed,
        per_kind,
    ));
    choices.extend(ranked(
        RelationKind::Serie,
        (names.series.list.iter())
            .filter(|s| !series.contains(&s.id.as_str()))
            .map(|s| (s.id.as_str(), Candidate::new(&s.name, s.alt.as_ref()))),
        typed,
        per_kind,
    ));
    choices.extend(ranked(
        RelationKind::Movie,
        (names.movies.list.iter())
            .filter(|m| !movies.contains(&m.id))
            .map(|m| (m.id.as_str(), Candidate::new(&m.name, None))),
        typed,
        per_kind,
    ));
    choices.extend(ranked(
        RelationKind::Book,
        (names.books.list.iter())
            .filter(|b| !books.contains(&b.id))
            .map(|b| (b.id.as_str(), Candidate::new(&b.name, None))),
        typed,
        per_kind,
    ));
    choices
}

/// Whether `typed` names nothing of `kind` exactly (without case or accents, spaces
/// around left out): the "Add" field offers to create it.
pub fn can_create(typed: &str, names: &Names, kind: RelationKind) -> bool {
    let typed = fold(typed.trim());
    !typed.is_empty() && !(names.names_of(kind).into_iter()).any(|name| fold(name.trim()) == typed)
}

/// The queue action adding a relation to a media. A tag goes without a confidence: it
/// validates one the server's model set. A series is added whole (no season or
/// episode). A movie or a book replaces the media's one.
#[cfg(feature = "mirror")]
pub fn add_action(media: &str, kind: RelationKind, id: &str) -> Action {
    let media = media.to_owned();
    let reference = || MediaItemReference {
        id: id.to_owned(),
        conf: None,
    };
    match kind {
        RelationKind::Person => Action::MediaAddPeople {
            media,
            people: vec![reference()],
        },
        RelationKind::Tag => Action::MediaAddTags {
            media,
            tags: vec![reference()],
        },
        RelationKind::Serie => Action::MediaAddSeries {
            media,
            series: vec![FileEpisode {
                id: id.to_owned(),
                season: None,
                episode: None,
                episode_to: None,
            }],
        },
        RelationKind::Movie => Action::MediaMovie {
            media,
            movie: id.to_owned(),
        },
        RelationKind::Book => Action::MediaBook {
            media,
            book: id.to_owned(),
        },
    }
}

/// The queue action removing a chip's relation from a media (a series entry by its
/// season and episode; a movie or a book needs a server with `removeMovie` and
/// `removeBook`, an older one leaving it).
#[cfg(feature = "mirror")]
pub fn remove_action(media: &str, chip: &Chip) -> Action {
    let media = media.to_owned();
    match chip.kind {
        RelationKind::Person => Action::MediaRemovePeople {
            media,
            people: vec![chip.id.clone()],
        },
        RelationKind::Tag => Action::MediaRemoveTags {
            media,
            tags: vec![chip.id.clone()],
        },
        RelationKind::Serie => Action::MediaRemoveSeries {
            media,
            series: vec![FileEpisode {
                id: chip.id.clone(),
                season: chip.season,
                episode: chip.episode,
                episode_to: None,
            }],
        },
        RelationKind::Movie => Action::MediaRemoveMovie {
            media,
            movie: chip.id.clone(),
        },
        RelationKind::Book => Action::MediaRemoveBook {
            media,
            book: chip.id.clone(),
        },
    }
}

/// The queue action adding tags copied from another media (with their confidence).
#[cfg(feature = "mirror")]
pub fn paste_tags_action(media: &str, tags: &[MediaItemReference]) -> Action {
    Action::MediaAddTags {
        media: media.to_owned(),
        tags: tags.to_vec(),
    }
}

/// A place typed by the user: "48.8566, 2.3522" (a comma, spaces, or both between the
/// two) to (lat, long). `None` when it is not two numbers, or not a place on Earth.
pub fn parse_place(text: &str) -> Option<(f64, f64)> {
    let parts: Vec<&str> = (text.split(|c: char| c == ',' || c.is_whitespace()))
        .filter(|p| !p.is_empty())
        .collect();
    let [lat, long] = parts.as_slice() else {
        return None;
    };
    let (lat, long) = (lat.parse::<f64>().ok()?, long.parse::<f64>().ok()?);
    let valid = lat.is_finite() && long.is_finite() && lat.abs() <= 90. && long.abs() <= 180.;
    valid.then_some((lat, long))
}

/// A face found in a media.
#[derive(Debug, Clone, PartialEq)]
pub struct FaceRow {
    pub id: String,
    /// The person it was given to.
    pub person: Option<Chip>,
    /// How sure the detector is: "92%".
    pub confidence: Option<String>,
}

/// A media's faces: given to a person, and not.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Faces {
    pub assigned: Vec<FaceRow>,
    pub unassigned: Vec<FaceRow>,
}

/// A media's faces (`LibraryApi::get_media_faces`) as the panel lists them, in the
/// order given.
pub fn faces(faces: Vec<FaceEmbedding>, names: &Names) -> Faces {
    let mut rows = Faces::default();
    for face in faces {
        let row = FaceRow {
            person: (face.person_id.as_deref())
                .filter(|id| !id.is_empty())
                .map(|id| Chip::new(names, RelationKind::Person, id, None)),
            confidence: (face.confidence)
                .filter(|c| c.is_finite() && *c > 0.)
                .map(|c| format!("{}%", (c * 100.).round() as i64)),
            id: face.id,
        };
        if row.person.is_some() {
            rows.assigned.push(row);
        } else {
            rows.unassigned.push(row);
        }
    }
    rows
}

/// Whether a media plays as a video.
pub fn is_video(media: &Media) -> bool {
    media.kind == FileType::Video || media.mimetype.starts_with("video/")
}

/// Whether a media has relations, whose names need reading.
pub fn has_relations(media: &MediaItem) -> bool {
    media.relations.as_ref().is_some_and(|r| {
        r.people.as_ref().is_some_and(|p| !p.is_empty())
            || r.tags.as_ref().is_some_and(|t| !t.is_empty())
            || r.series.as_ref().is_some_and(|s| !s.is_empty())
            || r.movies.as_ref().is_some_and(|m| !m.is_empty())
            || r.books.as_ref().is_some_and(|b| !b.is_empty())
    })
}

/// An OpenStreetMap page centred on the media's place.
pub fn map_url(media: &Media) -> Option<String> {
    let (lat, long) = (media.lat?, media.long?);
    Some(format!(
        "https://www.openstreetmap.org/?mlat={lat:.6}&mlon={long:.6}#map=15/{lat:.6}/{long:.6}"
    ))
}

/// The size a photo shows at before its file is read: the media's, its sides swapped
/// when its EXIF orientation turns it a quarter (5 to 8).
pub fn shown_size(media: &Media) -> (u64, u64) {
    let (w, h) = (
        media.width.unwrap_or(0) as u64,
        media.height.unwrap_or(0) as u64,
    );
    if media.orientation.is_some_and(|o| (5..=8).contains(&o)) {
        (h, w)
    } else {
        (w, h)
    }
}

fn dimensions(media: &Media) -> Option<String> {
    let (width, height) = (media.width?, media.height?);
    let megapixels = (width * height) as f64 / 1_000_000.;
    Some(if media.kind == FileType::Photo && megapixels >= 1. {
        format!("{width} × {height} ({megapixels:.0} MP)")
    } else {
        format!("{width} × {height}")
    })
}

#[cfg(test)]
mod tests;