redseat-api 0.20.0

Rust client for Redseat media servers
Documentation
//! A server's Overview, the first page of its settings (the web app's
//! `servers/[serverid]/settings/+page.svelte`): what the user is on the server, how
//! this device reaches it, the addresses it reports to the cloud, and how to take it
//! out of the user's servers.
//!
//! Everything comes from the server as the cloud lists it ([`CloudServer`]) and, for
//! the connection, from its copy ([`Connection::of`]).

use crate::call::Call;
use crate::cloud::{CloudServer, calls};
use crate::direct::{CandidateKind, candidate_kind};

use super::text;

/// What the user is on a server, as the cloud says.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Membership {
    /// Registered the server: may delete it.
    Owner,
    /// Has access: invited, and the server reported it.
    Member,
    /// Only saved in the user's list: the server has not confirmed any access.
    Saved,
}

impl Membership {
    /// What `user_id` is on `server`.
    pub fn of(server: &CloudServer, user_id: &str) -> Self {
        if server.owned_by(user_id) {
            Membership::Owner
        } else if server.member == Some(false) {
            Membership::Saved
        } else {
            Membership::Member
        }
    }

    /// Its badge: "Owner", "Member", "Saved".
    pub fn label(self) -> &'static str {
        match self {
            Membership::Owner => "Owner",
            Membership::Member => "Member",
            Membership::Saved => "Saved",
        }
    }

    /// What it means, in a sentence.
    pub fn description(self) -> &'static str {
        match self {
            Membership::Owner => "You registered this server.",
            Membership::Member => "The server shares its libraries with you.",
            Membership::Saved => "Saved in your list. The server has not confirmed your access.",
        }
    }
}

/// Which way this device reaches the server.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Route {
    /// Direct HTTPS to a local network address.
    LocalNetwork,
    /// Direct HTTPS to a public IPv4 or IPv6 address.
    Internet,
    /// HTTPS to the server's custom domain, served by its own reverse proxy.
    CustomDomain,
    /// An address the cloud does not list for the server.
    Other,
}

impl Route {
    /// The route of `base_url`, the address the copy is connected to.
    pub fn of(server: &CloudServer, base_url: &str) -> Self {
        match candidate_kind(server, base_url) {
            Some(CandidateKind::Lan) => Route::LocalNetwork,
            Some(CandidateKind::Ipv4 | CandidateKind::Ipv6) => Route::Internet,
            Some(CandidateKind::Domain) => Route::CustomDomain,
            None => Route::Other,
        }
    }

    /// "Direct · local network", "Direct · internet", "Custom domain", "Other address".
    pub fn label(self) -> &'static str {
        match self {
            Route::LocalNetwork => "Direct · local network",
            Route::Internet => "Direct · internet",
            Route::CustomDomain => "Custom domain",
            Route::Other => "Other address",
        }
    }

    /// What it means, in a sentence.
    pub fn description(self) -> &'static str {
        match self {
            Route::LocalNetwork => "HTTPS straight to the server on your local network.",
            Route::Internet => "HTTPS straight to the server over the internet.",
            Route::CustomDomain => {
                "HTTPS to the server's custom domain, through its own reverse proxy."
            }
            Route::Other => "An address the cloud does not list for this server.",
        }
    }
}

/// How this device reaches the server now.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Connection {
    pub connected: bool,
    /// "Connected · Direct · local network", "Connecting…", "Offline", "Not connected".
    pub status: String,
    /// While connected: the way it goes.
    pub route: Option<Route>,
}

#[cfg(feature = "mirror")]
impl Connection {
    /// The connection of `copy`, a copy of `server`.
    pub fn of(server: &CloudServer, copy: &super::ServerCopy) -> Self {
        use super::Reach;
        let (connected, status) = match copy.reach() {
            Reach::Connected => (true, "Connected"),
            Reach::Connecting => (false, "Connecting…"),
            Reach::Offline { .. } => (false, "Offline"),
            Reach::Disconnected => (false, "Not connected"),
        };
        let route = connected
            .then(|| copy.base())
            .flatten()
            .map(|base| Route::of(server, &base.url));
        let status = match route {
            Some(route) => format!("{status} · {}", route.label()),
            None => status.to_owned(),
        };
        Connection {
            connected,
            status,
            route,
        }
    }
}

/// An address the server reported for direct HTTPS.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Address {
    /// "LAN", "IPv4" or "IPv6".
    pub kind: &'static str,
    pub value: String,
}

/// How the user takes the server out of their servers: what they are on it decides.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Removal {
    /// The owner unregisters it, for everyone.
    Delete,
    /// A member leaves it.
    Leave,
    /// A server only saved is forgotten.
    Remove,
}

impl Removal {
    pub fn of(membership: Membership) -> Self {
        match membership {
            Membership::Owner => Removal::Delete,
            Membership::Member => Removal::Leave,
            Membership::Saved => Removal::Remove,
        }
    }

    /// The row's title: "Delete this server".
    pub fn title(self) -> &'static str {
        match self {
            Removal::Delete => "Delete this server",
            Removal::Leave => "Leave this server",
            Removal::Remove => "Remove from your servers",
        }
    }

    /// What it does, under the title.
    pub fn description(self) -> &'static str {
        match self {
            Removal::Delete => {
                "Unregister it from Redseat and remove it for everyone it is shared with. \
                 Media on the server is kept."
            }
            Removal::Leave => {
                "Remove it from your servers. You need a new invitation to come back."
            }
            Removal::Remove => "The server has not confirmed your access. Only your list changes.",
        }
    }

    /// The button that asks first: "Delete Server…".
    pub fn button(self) -> &'static str {
        match self {
            Removal::Delete => "Delete Server…",
            Removal::Leave => "Leave Server…",
            Removal::Remove => "Remove Server…",
        }
    }

    /// The question asked: "Delete “Home”?".
    pub fn question(self, name: &str) -> String {
        let verb = match self {
            Removal::Delete => "Delete",
            Removal::Leave => "Leave",
            Removal::Remove => "Remove",
        };
        format!("{verb} “{name}”?")
    }

    /// What follows, under the question.
    pub fn consequence(self) -> &'static str {
        match self {
            Removal::Delete => {
                "It is unregistered from Redseat and removed for every user it is shared \
                 with. Media stored on the server is kept. This can’t be undone."
            }
            Removal::Leave => {
                "It is removed from your servers. You need a new invitation to come back."
            }
            Removal::Remove => "It is removed from your list.",
        }
    }

    /// The button that does it: "Delete", "Leave", "Remove".
    pub fn confirm(self) -> &'static str {
        match self {
            Removal::Delete => "Delete",
            Removal::Leave => "Leave",
            Removal::Remove => "Remove",
        }
    }

    /// While it runs: "Deleting…".
    pub fn working(self) -> &'static str {
        match self {
            Removal::Delete => "Deleting…",
            Removal::Leave => "Leaving…",
            Removal::Remove => "Removing…",
        }
    }

    /// Whether the server's name must be typed first: deleting cannot be undone.
    pub fn asks_name(self) -> bool {
        self == Removal::Delete
    }

    /// The field asking it: "Type “Home” to confirm".
    pub fn name_prompt(self, name: &str) -> String {
        format!("Type “{}” to confirm", name.trim())
    }

    /// Whether `typed` lets it go on: the server's name, when [`Self::asks_name`].
    /// Names are not trimmed at registration: neither side counts its spaces.
    pub fn confirmed(self, name: &str, typed: &str) -> bool {
        !self.asks_name() || typed.trim() == name.trim()
    }

    /// What it did, once done: "“Home” was deleted.".
    pub fn done(self, name: &str) -> String {
        match self {
            Removal::Delete => format!("“{name}” was deleted."),
            Removal::Leave => format!("You left “{name}”."),
            Removal::Remove => format!("“{name}” was removed from your servers."),
        }
    }

    /// Why it failed: "Couldn’t delete “Home”: …".
    pub fn failure(self, name: &str, error: &crate::Error) -> String {
        let verb = match self {
            Removal::Delete => "delete",
            Removal::Leave => "leave",
            Removal::Remove => "remove",
        };
        let reason = match error.kind() {
            crate::ErrorKind::Network | crate::ErrorKind::Timeout => {
                "the Redseat cloud can’t be reached. Check your connection.".to_owned()
            }
            _ => error.to_string(),
        };
        format!("Couldn’t {verb} “{name}”: {reason}")
    }

    /// The cloud call that does it, with the user's session token.
    pub fn call(self, server_id: &str, session_token: &str) -> Call<()> {
        match self {
            Removal::Delete => calls::delete_server(server_id, session_token),
            Removal::Leave | Removal::Remove => {
                calls::remove_saved_server(server_id, session_token)
            }
        }
    }
}

/// A server's Overview.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServerOverview {
    pub id: String,
    /// Its name, else its id.
    pub name: String,
    pub membership: Membership,
    /// Its custom domain, with its port when not 443: "media.example.org:8443".
    pub domain: Option<String>,
    /// The name direct HTTPS answers on: "*.abc.redseat.direct:8443".
    pub direct_host: Option<String>,
    /// When the server last reported its addresses, in Unix milliseconds.
    pub reported_at: Option<i64>,
    /// The addresses it reported, local network first.
    pub addresses: Vec<Address>,
    pub removal: Removal,
}

impl ServerOverview {
    /// The Overview of `server` for the user `user_id`. The cloud gives a server's
    /// addresses and domain only to users with access.
    pub fn new(server: &CloudServer, user_id: &str) -> Self {
        let membership = Membership::of(server, user_id);
        let with_port = |host: &str, port: Option<u16>| match port {
            None | Some(443) => host.to_owned(),
            Some(port) => format!("{host}:{port}"),
        };
        let domain = server
            .domain
            .as_deref()
            .filter(|d| !d.is_empty())
            .map(|d| with_port(d, server.port));
        let direct = server.direct.as_ref();
        let addresses = direct
            .map(|direct| {
                let found = &direct.addresses;
                let lan = found.lan.iter().map(|a| ("LAN", a));
                let ipv4 = found.ipv4.iter().map(|a| ("IPv4", a));
                let ipv6 = found.ipv6.iter().map(|a| ("IPv6", a));
                lan.chain(ipv4)
                    .chain(ipv6)
                    .map(|(kind, value)| Address {
                        kind,
                        value: value.clone(),
                    })
                    .collect()
            })
            .unwrap_or_default();
        ServerOverview {
            id: server.id.clone(),
            name: server
                .name
                .clone()
                .filter(|n| !n.trim().is_empty())
                .unwrap_or_else(|| server.id.clone()),
            membership,
            domain,
            direct_host: direct
                .map(|d| with_port(&format!("*.{}.{}", d.label, d.zone), Some(d.port))),
            reported_at: direct.map(|d| d.updated_at).filter(|at| *at > 0),
            addresses,
            removal: Removal::of(membership),
        }
    }

    /// When the server last reported its addresses, from `now` (Unix milliseconds):
    /// "5 minutes ago".
    pub fn reported(&self, now: i64) -> Option<String> {
        self.reported_at.map(|at| text::ago(at, now))
    }
}

#[cfg(test)]
mod tests;