redseat-api 0.15.0

Rust client for Redseat media servers
Documentation
//! A media's details as label and value rows, as a details panel lists them, and what
//! a viewer needs to know about a media before reading its file.

use std::collections::HashMap;

use crate::library::MediaItem;
use crate::types::media::{FileType, Media};
use crate::types::person::Person;
use crate::types::tag::Tag;

use super::text;

/// Names of a library's people and tags, by id: medias name them by id only.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Names {
    people: HashMap<String, String>,
    tags: HashMap<String, String>,
}

impl Names {
    pub fn new(people: Vec<Person>, tags: Vec<Tag>) -> Self {
        Names {
            people: people.into_iter().map(|p| (p.id, p.name)).collect(),
            tags: tags.into_iter().map(|t| (t.id, t.name)).collect(),
        }
    }
}

/// 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,
}

/// 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 people or tags, 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())
    })
}

/// The rows of the details after the media's name and date (each app writes those its
/// own way: the date in the person's time zone): only the ones the media has a value
/// for. People and tags whose name is unknown are left out of their row.
pub fn details(media: &MediaItem, names: &Names) -> Vec<Detail> {
    let item = &media.item;
    let mut rows = Vec::new();
    let mut push = |label: &'static str, value: Option<String>| {
        if let Some(value) = value.filter(|v| !v.is_empty()) {
            rows.push(Detail { label, value });
        }
    };
    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 && is_video(item))
            .map(|d| text::duration(d as u64)),
    );
    push("Camera", item.model.clone());
    push("Place", place(item));
    let relations = media.relations.as_ref();
    push(
        "People",
        (relations.and_then(|r| r.people.as_ref()))
            .map(|people| join_names(people.iter().map(|p| &p.id), &names.people)),
    );
    push(
        "Tags",
        (relations.and_then(|r| r.tags.as_ref()))
            .map(|tags| join_names(tags.iter().map(|t| &t.id), &names.tags)),
    );
    rows
}

/// 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 join_names<'a>(
    ids: impl Iterator<Item = &'a String>,
    names: &HashMap<String, String>,
) -> String {
    ids.filter_map(|id| names.get(id).map(String::as_str))
        .collect::<Vec<_>>()
        .join(", ")
}

fn place(media: &Media) -> Option<String> {
    Some(format!("{:.5}, {:.5}", media.lat?, media.long?))
}

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 {
    use super::*;
    use crate::types::Relations;
    use crate::types::media::MediaItemReference;

    fn reference(id: &str) -> MediaItemReference {
        MediaItemReference {
            id: id.into(),
            conf: None,
        }
    }

    fn tag(id: &str, name: &str) -> Tag {
        serde_json::from_value(serde_json::json!({
            "id": id, "name": name, "parent": null, "alt": null, "modified": 0, "added": 0,
            "generated": false, "path": format!("/{name}")
        }))
        .unwrap()
    }

    #[test]
    fn details_list_what_the_media_has() {
        let media = MediaItem {
            item: Media {
                id: "m".into(),
                name: "IMG_0001.jpg".into(),
                kind: FileType::Photo,
                mimetype: "image/jpeg".into(),
                size: Some(3_500_000),
                created: Some(1_700_000_000_000),
                width: Some(4032),
                height: Some(3024),
                model: Some("iPhone 15".into()),
                lat: Some(48.8566),
                long: Some(2.3522),
                ..Default::default()
            },
            relations: Some(Relations {
                people: Some(vec![reference("p1"), reference("unknown")]),
                tags: Some(vec![reference("t1"), reference("t2")]),
                ..Default::default()
            }),
        };
        let names = Names::new(
            vec![Person {
                id: "p1".into(),
                name: "Alice".into(),
                ..Default::default()
            }],
            vec![tag("t1", "beach"), tag("t2", "summer")],
        );
        let rows: Vec<(&str, String)> = (details(&media, &names).into_iter())
            .map(|d| (d.label, d.value))
            .collect();
        let row = |l: &'static str, v: &str| (l, v.to_owned());
        assert_eq!(
            rows,
            [
                row("Type", "image/jpeg"),
                row("Size", "3.3 MB"),
                row("Dimensions", "4032 × 3024 (12 MP)"),
                row("Camera", "iPhone 15"),
                row("Place", "48.85660, 2.35220"),
                row("People", "Alice"),
                row("Tags", "beach, summer"),
            ]
        );
        assert!(has_relations(&media));
        assert_eq!(
            map_url(&media.item).unwrap(),
            "https://www.openstreetmap.org/?mlat=48.856600&mlon=2.352200#map=15/48.856600/2.352200"
        );

        let video = MediaItem {
            item: Media {
                name: "clip.mp4".into(),
                kind: FileType::Video,
                mimetype: "video/mp4".into(),
                duration: Some(65),
                ..Default::default()
            },
            relations: None,
        };
        let labels: Vec<&str> = (details(&video, &Names::default()).into_iter())
            .map(|d| d.label)
            .collect();
        assert_eq!(labels, ["Type", "Duration"]);
        assert!(is_video(&video.item));
        assert!(!has_relations(&video));
    }

    #[test]
    fn a_turned_photo_shows_its_sides_swapped() {
        let turned = Media {
            width: Some(4000),
            height: Some(3000),
            orientation: Some(6),
            ..Default::default()
        };
        assert_eq!(shown_size(&turned), (3000, 4000));
        let upright = Media {
            orientation: Some(1),
            ..turned
        };
        assert_eq!(shown_size(&upright), (4000, 3000));
    }
}