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;
#[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))
}
}
#[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())
}
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)
}
pub fn people(&self) -> impl Iterator<Item = &Person> {
self.people.list.iter()
}
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)
}
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),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Detail {
pub label: &'static str,
pub value: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RelationKind {
Person,
Tag,
Serie,
Movie,
Book,
}
impl RelationKind {
pub const ALL: [RelationKind; 5] = [
RelationKind::Person,
RelationKind::Tag,
RelationKind::Serie,
RelationKind::Movie,
RelationKind::Book,
];
pub fn name(self) -> &'static str {
match self {
RelationKind::Person => "person",
RelationKind::Tag => "tag",
RelationKind::Serie => "series",
RelationKind::Movie => "movie",
RelationKind::Book => "book",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Chip {
pub kind: RelationKind,
pub id: String,
pub name: String,
pub detail: Option<String>,
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,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TagChip {
pub chip: Chip,
pub confidence: Option<u16>,
pub to_validate: bool,
pub generated: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateKind {
Taken,
Added,
Modified,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DateRow {
pub kind: DateKind,
pub label: &'static str,
pub ms: i64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Place {
pub lat: f64,
pub long: f64,
pub label: String,
pub map_url: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Origin {
pub label: String,
pub url: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Access {
pub edit: bool,
pub delete: bool,
pub admin: bool,
}
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,
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct MediaDetails {
pub id: String,
pub kind: FileType,
pub name: String,
pub description: Option<String>,
pub rating: Option<u8>,
pub dates: Vec<DateRow>,
pub info: Vec<Detail>,
pub place: Option<Place>,
pub origin: Option<Origin>,
pub original: Option<String>,
pub pages: Option<usize>,
pub people: Vec<Chip>,
pub series: Vec<Chip>,
pub movie: Option<Chip>,
pub book: Option<Chip>,
pub tags: Vec<TagChip>,
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,
}
}
}
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,
}
}
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(" · "))
}
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,
},
}
}
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
}
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(" · "))
}
#[derive(Debug, Clone, PartialEq)]
pub struct AddChoice {
pub kind: RelationKind,
pub id: String,
pub name: String,
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,
}
}
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)
}
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
}
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)
}
#[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(),
},
}
}
#[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(),
},
}
}
#[cfg(feature = "mirror")]
pub fn paste_tags_action(media: &str, tags: &[MediaItemReference]) -> Action {
Action::MediaAddTags {
media: media.to_owned(),
tags: tags.to_vec(),
}
}
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))
}
#[derive(Debug, Clone, PartialEq)]
pub struct FaceRow {
pub id: String,
pub person: Option<Chip>,
pub confidence: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Faces {
pub assigned: Vec<FaceRow>,
pub unassigned: Vec<FaceRow>,
}
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
}
pub fn is_video(media: &Media) -> bool {
media.kind == FileType::Video || media.mimetype.starts_with("video/")
}
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())
})
}
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}"
))
}
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;