~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
254 lines · 8.5 KB Raw History
//! Apps: what an account's records and a query are of, as people know them.
//! An app is the domain behind an NSID, its first two segments reversed
//! (`app.bsky.feed.post` is `bsky.app`'s, `dev.knotless.repo`
//! `knotless.dev`'s), needing no registration. Its name is the one a
//! bundled view of that domain gives (`"app": "Bluesky"`), else the domain
//! itself; its icon its site's favicon, as the server's own `/icon/<domain>`
//! serves it (`icons`); its entry points the launchers its bundled method
//! views offer (`launch`).

use crate::view;
use serde_json::{Value, json};
use std::sync::LazyLock;

/// The domain of the app an NSID is of: its first two segments, reversed
/// (`app.bsky.feed.post` is `bsky.app`'s); none for what is no NSID.
pub fn domain(nsid: &str) -> Option<String> {
    if !atproto::syntax::is_nsid(nsid) {
        return None;
    }
    let mut segments = nsid.split('.');
    let (tld, name) = (segments.next()?, segments.next()?);
    Some(format!("{name}.{tld}").to_ascii_lowercase())
}

/// Each domain a bundled view names the app of, and that name: the first
/// view's, in their ids' order.
static NAMES: LazyLock<Vec<(String, String)>> = LazyLock::new(|| {
    let mut names: Vec<(String, String)> = Vec::new();
    let named = view::bundled()
        .iter()
        .filter_map(|b| Some((app_of(&b.view)?, b.view.app.as_ref()?)));
    for (d, app) in named {
        if !names.iter().any(|(known, _)| *known == d) {
            names.push((d, app.clone()));
        }
    }
    names
});

/// The domain of the app a view is of: an app page's own, else its
/// collection's or method's.
fn app_of(v: &view::View) -> Option<String> {
    v.domain.clone().or_else(|| domain(v.drawn()))
}

/// The app a view is of, where that app has a page (a bundled `domain`
/// view): where an account the view names opens.
pub fn with_page(v: &view::View) -> Option<String> {
    app_of(v).filter(|d| view::for_domain(d).is_some())
}

/// An app's name: a bundled view's for its domain, else the domain.
pub fn name(domain: &str) -> String {
    NAMES
        .iter()
        .find(|(d, _)| d == domain)
        .map_or_else(|| domain.to_string(), |(_, n)| n.clone())
}

/// An app's icon, as the server at `origin` serves it.
pub fn icon(origin: &str, domain: &str) -> String {
    format!("{origin}/icon/{domain}")
}

/// A place an app opens at: a launcher a bundled method view of it offers,
/// its title and the `query` call it makes, as a tree's `open` names one.
#[derive(Clone, Debug, PartialEq)]
pub struct Entry {
    pub title: String,
    pub call: Value,
}

/// The app `app`'s entry points, in the views' order: every launcher its
/// bundled method views offer, its params made the person's (`me`: their
/// DID and handle). With no one signed in, those that need someone are
/// left out: one naming the person (`$me`) or feeds by name
/// (`feeds::names_feeds`, as "Saved feeds"), or one whose view's query
/// needs an account (its `signIn`).
pub fn entries(app: &str, me: Option<(&str, Option<&str>)>) -> Vec<Entry> {
    let mut out = Vec::new();
    for b in view::bundled() {
        let v = &b.view;
        let Some(method) = v.method.as_deref() else {
            continue;
        };
        if domain(method).as_deref() != Some(app) {
            continue;
        }
        for l in &v.launch {
            let needs_someone =
                l.names_me() || v.sign_in.is_some() || crate::feeds::names_feeds(method, &l.params);
            let params = match me {
                Some((did, handle)) => l.params_for(did, handle),
                None if needs_someone => None,
                None => Some(l.params.clone()),
            };
            let Some(params) = params else { continue };
            out.push(Entry {
                title: l.title.clone(),
                call: json!({ "name": "query", "args": { "method": method, "params": params } }),
            });
        }
    }
    out
}

/// An app an account uses: its domain, its name, and the account's
/// collections of it, in the account's order.
#[derive(Clone, Debug, PartialEq)]
pub struct App {
    pub domain: String,
    pub name: String,
    pub collections: Vec<String>,
}

/// An account's collections grouped by app: the app with the most
/// collections first, ties by domain. What is no NSID is left out.
pub fn group(collections: &[String]) -> Vec<App> {
    let mut apps: Vec<App> = Vec::new();
    for c in collections {
        let Some(d) = domain(c) else { continue };
        match apps.iter_mut().find(|a| a.domain == d) {
            Some(a) => a.collections.push(c.clone()),
            None => apps.push(App {
                name: name(&d),
                domain: d,
                collections: vec![c.clone()],
            }),
        }
    }
    apps.sort_by(|a, b| {
        b.collections
            .len()
            .cmp(&a.collections.len())
            .then_with(|| a.domain.cmp(&b.domain))
    });
    apps
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn domains() {
        assert_eq!(
            domain("social.grain.gallery").as_deref(),
            Some("grain.social")
        );
        assert_eq!(domain("not an nsid"), None);
        assert_eq!(
            icon("https://hud.example", "plyr.fm"),
            "https://hud.example/icon/plyr.fm"
        );
    }

    /// Every bundled view names its app, and the views of one domain name
    /// it alike; a domain no view names is its own name.
    #[test]
    fn names_are_the_bundled_views() {
        for b in view::bundled() {
            let d = app_of(&b.view).unwrap();
            assert_eq!(b.view.app.as_ref(), Some(&name(&d)), "{}", b.id);
        }
        assert_eq!(name("bsky.app"), "Bluesky");
        assert_eq!(name("knotless.dev"), "knotless");
        assert_eq!(name("plyr.fm"), "plyr.fm");
        assert_eq!(name("grain.social"), "Grain");
        assert_eq!(name("standard.site"), "standard.site");
        assert_eq!(name("leaflet.pub"), "leaflet.pub");
    }

    #[test]
    fn grouped_by_app() {
        let collections: Vec<String> = [
            "app.bsky.actor.profile",
            "fm.plyr.like",
            "app.bsky.feed.post",
            "pub.leaflet.document",
            "nope",
            "fm.plyr.list",
            "app.bsky.feed.like",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let apps = group(&collections);
        let summary: Vec<(&str, &str, usize)> = apps
            .iter()
            .map(|a| (a.domain.as_str(), a.name.as_str(), a.collections.len()))
            .collect();
        assert_eq!(
            summary,
            [
                ("bsky.app", "Bluesky", 3),
                ("plyr.fm", "plyr.fm", 2),
                ("leaflet.pub", "leaflet.pub", 1),
            ]
        );
        assert_eq!(
            apps[0].collections,
            [
                "app.bsky.actor.profile",
                "app.bsky.feed.post",
                "app.bsky.feed.like"
            ]
        );
        assert!(group(&[]).is_empty());
    }

    /// An app's entry points are its views' launchers; signed out, those
    /// that need someone signed in are left out.
    #[test]
    fn entry_points() {
        let titles = |app: &str, me: Option<(&str, Option<&str>)>| -> Vec<String> {
            entries(app, me).into_iter().map(|e| e.title).collect()
        };
        assert_eq!(titles("bsky.app", None), ["Discover"]);
        let me = Some(("did:plc:me", Some("me.test")));
        assert_eq!(
            titles("bsky.app", me),
            [
                "Posts",
                "Discover",
                "Saved feeds",
                "Notifications",
                "Following"
            ]
        );
        // Feeds by name are the account's: a call the query tool resolves for it.
        let yours = &entries("bsky.app", me)[2].call;
        assert_eq!(yours["args"]["params"], json!({ "feeds": "saved" }));
        assert_eq!(titles("knotless.dev", None), ["Everyone’s activity"]);
        assert_eq!(
            titles("plyr.fm", None),
            [
                "Latest",
                "Trending this week",
                "Top this month",
                "Top of all time"
            ]
        );
        let mine = entries("bsky.app", me);
        assert_eq!(
            mine[0].call,
            json!({ "name": "query", "args": { "method": "app.bsky.feed.getAuthorFeed",
                    "params": { "actor": "did:plc:me", "filter": "posts_no_replies" } } })
        );
        assert_eq!(
            mine[4].call,
            json!({ "name": "query", "args": { "method": "app.bsky.feed.getTimeline", "params": {} } })
        );
    }
}