~ 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
484 lines · 18.7 KB Raw History
//! Feeds by name, for a signed-in account: its saved feeds, from its
//! preferences (`app.bsky.actor.getPreferences`, which its PDS answers),
//! named by their generators' display names (`app.bsky.feed.getFeedGenerators`,
//! from the AppView) and kept five minutes. Then `query
//! app.bsky.feed.getFeed` takes a feed's name where its at-uri goes ("For
//! You"), `following` (or `timeline`, `home`) is the timeline, and `query
//! app.bsky.feed.getFeedGenerators` takes `saved` or `pinned` for the
//! account's own. Signed out, a name asks for sign-in.

use crate::Hud;
use crate::interactions::APPVIEW;
use crate::oauth::Account;
use crate::pds::error_name;
use crate::tools::Refusal;
use crate::uri::AtUri;
use serde_json::{Map, Value};
use std::sync::Arc;
use std::time::Duration;

const GET_FEED: &str = "app.bsky.feed.getFeed";
const GET_TIMELINE: &str = "app.bsky.feed.getTimeline";
const GET_GENERATORS: &str = "app.bsky.feed.getFeedGenerators";
pub(crate) const GET_PREFERENCES: &str = "app.bsky.actor.getPreferences";
/// The queries that take feeds by name (`names_feeds`): a view drawing one
/// has HUD ask to read preferences (`view::Views::names_feeds`).
pub(crate) const NAMING: [&str; 2] = [GET_FEED, GET_GENERATORS];
/// A feed generator's record collection.
const GENERATOR: &str = "app.bsky.feed.generator";
/// The preferences saved feeds are in: now, and before.
const SAVED_V2: &str = "app.bsky.actor.defs#savedFeedsPrefV2";
const SAVED_V1: &str = "app.bsky.actor.defs#savedFeedsPref";
/// The names that mean the timeline.
const TIMELINE: [&str; 3] = ["following", "timeline", "home"];
/// What the timeline is called among the saved feeds.
const FOLLOWING: &str = "Following";

/// Whether a query's params name feeds as a person names them, which
/// `feeds_by_name` makes at-uris for the signed-in account alone: a
/// `getFeed` of a name, a `getFeedGenerators` of `saved` or `pinned`. Such
/// params need an account; `stand_in` gives the at-uris a check of them
/// against the lexicon takes in their place.
pub fn names_feeds(method: &str, params: &Map<String, Value>) -> bool {
    match method {
        GET_FEED => params
            .get("feed")
            .and_then(Value::as_str)
            .is_some_and(|f| !f.trim().starts_with("at://")),
        GET_GENERATORS => params
            .get("feeds")
            .and_then(Value::as_str)
            .is_some_and(|w| matches!(w.trim().to_lowercase().as_str(), "saved" | "pinned")),
        _ => false,
    }
}

/// `params` with any feed named as a person names them (`names_feeds`)
/// replaced by a feed generator's at-uri, as `feeds_by_name` would put one.
pub fn stand_in(method: &str, params: &mut Map<String, Value>) {
    if !names_feeds(method, params) {
        return;
    }
    let uri = Value::String(format!(
        "at://did:plc:abcdefghijklmnopqrstuvwx/{GENERATOR}/stand-in"
    ));
    match method {
        GET_FEED => {
            params.insert("feed".into(), uri);
        }
        _ => {
            params.insert("feeds".into(), Value::Array(vec![uri]));
        }
    }
}
/// How long an account's saved feeds are kept.
const KEEP: Duration = Duration::from_secs(300);
/// The most feeds named in one call of getFeedGenerators.
const NAMED_MAX: usize = 100;

/// A saved feed: its name, its generator's at-uri (none for the
/// timeline), and whether it is pinned.
#[derive(Clone, Debug, PartialEq)]
pub struct SavedFeed {
    pub name: String,
    pub uri: Option<String>,
    pub pinned: bool,
}

/// A saved feed's at-uri, if it is a generator's.
fn generator_uri(v: &Value) -> Option<String> {
    let u = AtUri::parse(v.as_str()?).ok()?;
    (u.collection == GENERATOR).then(|| v.as_str().unwrap_or_default().to_string())
}

/// The saved feeds an account's preferences hold, unnamed, in their order:
/// the newer kind of preference (`savedFeedsPrefV2`, its feeds and its
/// timeline; lists are left out) where there is one, else the older (its
/// pinned, then its other saved). A generator's name is filled later.
pub fn saved_of(prefs: &Value) -> Vec<SavedFeed> {
    let prefs = prefs["preferences"]
        .as_array()
        .map_or(&[][..], Vec::as_slice);
    let of = |t: &str| prefs.iter().find(|p| p["$type"] == t);
    if let Some(p) = of(SAVED_V2) {
        return p["items"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|i| {
                let pinned = i["pinned"] == Value::Bool(true);
                let uri = match i["type"].as_str()? {
                    "feed" => Some(generator_uri(&i["value"])?),
                    "timeline" => None,
                    _ => return None,
                };
                Some(SavedFeed {
                    name: if uri.is_none() {
                        FOLLOWING.into()
                    } else {
                        String::new()
                    },
                    uri,
                    pinned,
                })
            })
            .collect();
    }
    let Some(p) = of(SAVED_V1) else {
        return Vec::new();
    };
    let uris = |k: &str| -> Vec<String> {
        p[k].as_array()
            .into_iter()
            .flatten()
            .filter_map(generator_uri)
            .collect()
    };
    let pinned = uris("pinned");
    let mut out: Vec<SavedFeed> = pinned
        .iter()
        .map(|u| SavedFeed {
            name: String::new(),
            uri: Some(u.clone()),
            pinned: true,
        })
        .collect();
    for u in uris("saved") {
        if !pinned.contains(&u) {
            out.push(SavedFeed {
                name: String::new(),
                uri: Some(u),
                pinned: false,
            });
        }
    }
    out
}

/// The saved feeds' names, pinned first, for a refusal to list.
fn names(saved: &[SavedFeed]) -> String {
    let (pinned, rest): (Vec<&SavedFeed>, Vec<&SavedFeed>) = saved.iter().partition(|f| f.pinned);
    let all: Vec<&str> = pinned
        .iter()
        .chain(&rest)
        .map(|f| f.name.as_str())
        .collect();
    match all.len() {
        0 => "You have no saved feeds".into(),
        _ => format!("Your feeds: {}", all.join(", ")),
    }
}

/// The saved feed `name` names: one whose name it is (case and the space
/// around it aside), else the one whose name holds it; else why not, the
/// saved feeds named.
pub fn match_name<'a>(saved: &'a [SavedFeed], name: &str) -> Result<&'a str, String> {
    let want = name.trim().to_lowercase();
    let feeds: Vec<(&SavedFeed, &str)> = saved
        .iter()
        .filter_map(|f| Some((f, f.uri.as_deref()?)))
        .collect();
    if let Some((_, uri)) = feeds
        .iter()
        .find(|(f, _)| f.name.trim().to_lowercase() == want)
    {
        return Ok(uri);
    }
    let held: Vec<&(&SavedFeed, &str)> = feeds
        .iter()
        .filter(|(f, _)| !want.is_empty() && f.name.to_lowercase().contains(&want))
        .collect();
    let shown = crate::summary::one_line(name.trim(), 60);
    match held.as_slice() {
        [(_, uri)] => Ok(uri),
        [] => Err(format!(
            "No saved feed is named \"{shown}\". {}",
            names(saved)
        )),
        several => Err(format!(
            "\"{shown}\" names several saved feeds ({}). {}",
            several
                .iter()
                .map(|(f, _)| f.name.as_str())
                .collect::<Vec<_>>()
                .join(", "),
            names(saved)
        )),
    }
}

/// A feed's name for a saved feed whose generator gave none: its rkey. A
/// saved feed's uri is always a generator's at-uri (`generator_uri`).
fn fallback_name(uri: &str) -> String {
    AtUri::parse(uri).map(|u| u.rkey).unwrap_or_default()
}

impl Hud {
    /// An account's saved feeds, named: kept five minutes.
    pub async fn saved_feeds(&self, account: &Account) -> Result<Arc<Vec<SavedFeed>>, Refusal> {
        if let Some(kept) = self.saved_feeds.get(&account.did) {
            return Ok(kept);
        }
        let read = |what: &str, got: &crate::net::Fetched| -> Result<Value, Refusal> {
            if got.status != 200 {
                return Err(match error_name(&got.body) {
                    Some(e) => format!("Your {what} could not be read: {e} ({})", got.status),
                    None => format!("Your {what} could not be read ({})", got.status),
                }
                .into());
            }
            serde_json::from_slice(&got.body)
                .map_err(|_| Refusal::Error(format!("Your {what} could not be read")))
        };
        let got = self
            .pds_call(account, GET_PREFERENCES, &[], None, None)
            .await?;
        if error_name(&got.body).as_deref() == Some("ScopeMissingError") {
            let scope = format!("rpc:{GET_PREFERENCES}?aud=*");
            return Err(self.scope_refused(account, &scope).await);
        }
        let mut saved = saved_of(&read("preferences", &got)?);
        let uris: Vec<(String, String)> = saved
            .iter()
            .filter_map(|f| f.uri.clone())
            .take(NAMED_MAX)
            .map(|u| ("feeds".to_string(), u))
            .collect();
        let named: Map<String, Value> = if uris.is_empty() {
            Map::new()
        } else {
            let got = self
                .pds_call(account, GET_GENERATORS, &uris, None, Some(APPVIEW))
                .await?;
            read("feeds", &got)?["feeds"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(|g| {
                    let name = g["displayName"].as_str()?;
                    Some((g["uri"].as_str()?.to_string(), Value::String(name.into())))
                })
                .collect()
        };
        for f in &mut saved {
            if let Some(uri) = &f.uri {
                f.name = match named.get(uri).and_then(Value::as_str) {
                    Some(n) => crate::summary::one_line(n, 64),
                    None => fallback_name(uri),
                };
            }
        }
        let saved = Arc::new(saved);
        self.saved_feeds
            .put(account.did.clone(), saved.clone(), KEEP);
        Ok(saved)
    }

    /// A query's method and params with feeds named as a person names
    /// them made what the service takes: a `getFeed` of a feed's name, its
    /// at-uri, or of `following`, the timeline; a `getFeedGenerators` of
    /// `saved` or `pinned`, the account's own. Signed out, a name asks for
    /// sign-in. Anything else is left as it is.
    pub async fn feeds_by_name(
        &self,
        method: &str,
        params: &mut Map<String, Value>,
        account: Option<&Account>,
    ) -> Result<String, Refusal> {
        match method {
            GET_FEED => {
                let Some(feed) = params
                    .get("feed")
                    .and_then(Value::as_str)
                    .filter(|f| !f.trim().starts_with("at://"))
                    .map(str::to_string)
                else {
                    return Ok(method.into());
                };
                let account = account.ok_or(Refusal::SignIn)?;
                if TIMELINE.contains(&feed.trim().to_lowercase().as_str()) {
                    params.remove("feed");
                    return Ok(GET_TIMELINE.into());
                }
                let saved = self.saved_feeds(account).await?;
                let uri = match_name(&saved, &feed)?;
                params.insert("feed".into(), Value::String(uri.to_string()));
                Ok(method.into())
            }
            GET_GENERATORS => {
                let which = match params.get("feeds").and_then(Value::as_str) {
                    Some(w) if matches!(w.trim().to_lowercase().as_str(), "saved" | "pinned") => {
                        w.trim().to_lowercase()
                    }
                    _ => return Ok(method.into()),
                };
                let account = account.ok_or(Refusal::SignIn)?;
                let saved = self.saved_feeds(account).await?;
                let uris: Vec<Value> = saved
                    .iter()
                    .filter(|f| which == "saved" || f.pinned)
                    .filter_map(|f| f.uri.clone().map(Value::String))
                    .take(NAMED_MAX)
                    .collect();
                if uris.is_empty() {
                    return Err(format!("You have no {which} feeds").into());
                }
                params.insert("feeds".into(), Value::Array(uris));
                Ok(method.into())
            }
            _ => Ok(method.into()),
        }
    }
}

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

    #[test]
    fn stand_ins_for_names() {
        let mut p = json!({ "feed": "Discover" }).as_object().unwrap().clone();
        stand_in(GET_FEED, &mut p);
        assert_eq!(
            p["feed"],
            format!("at://did:plc:abcdefghijklmnopqrstuvwx/{GENERATOR}/stand-in")
        );
        let mut p = json!({ "feeds": "saved" }).as_object().unwrap().clone();
        stand_in(GET_GENERATORS, &mut p);
        assert_eq!(p["feeds"].as_array().unwrap().len(), 1);
    }

    /// A server signed in at a PDS answering `getPreferences` as given.
    async fn signed_in(status: u16, prefs: &'static str) -> (Arc<Hud>, Account) {
        let answer =
            move || async move { (axum::http::StatusCode::from_u16(status).unwrap(), prefs) };
        let app = axum::Router::new().route("/xrpc/{method}", axum::routing::get(answer));
        let pds = crate::tests::serve(app).await;
        crate::tests::signed_in("http://127.0.0.1:1", &pds)
    }

    #[tokio::test]
    async fn preferences_that_cannot_be_read() {
        for (status, prefs, why) in [
            (
                400,
                r#"{"error":"InvalidToken"}"#,
                "Your preferences could not be read: InvalidToken (400)",
            ),
            (500, "", "Your preferences could not be read (500)"),
            (200, "nope", "Your preferences could not be read"),
            (
                403,
                r#"{"error":"ScopeMissingError"}"#,
                "Your sign-in does not allow rpc:app.bsky.actor.getPreferences?aud=*",
            ),
        ] {
            let (hud, account) = signed_in(status, prefs).await;
            let refused = hud.saved_feeds(&account).await;
            assert_eq!(refused.err().unwrap(), Refusal::Error(why.into()));
        }
    }

    #[tokio::test]
    async fn names_of_feeds_with_none_saved() {
        let timeline = r#"{ "preferences": [{ "$type": "app.bsky.actor.defs#savedFeedsPrefV2",
            "items": [{ "type": "timeline", "value": "following", "pinned": true }] }] }"#;
        let (hud, account) = signed_in(200, timeline).await;
        let mut p = json!({ "feeds": " Pinned " }).as_object().unwrap().clone();
        assert_eq!(
            hud.feeds_by_name(GET_GENERATORS, &mut p, Some(&account))
                .await,
            Err(Refusal::Error("You have no pinned feeds".into()))
        );
        // Feeds named by at-uri, and other methods, are left as they are.
        let mut p = json!({ "feeds": ["at://did:plc:x/app.bsky.feed.generator/a"] })
            .as_object()
            .unwrap()
            .clone();
        let before = p.clone();
        let method = hud.feeds_by_name(GET_GENERATORS, &mut p, None).await;
        assert_eq!((method, &p), (Ok(GET_GENERATORS.to_string()), &before));
        let method = hud.feeds_by_name(GET_TIMELINE, &mut p, None).await;
        assert_eq!(method, Ok(GET_TIMELINE.to_string()));
    }

    fn feed(name: &str, rkey: &str, pinned: bool) -> SavedFeed {
        SavedFeed {
            name: name.into(),
            uri: Some(format!("at://did:plc:x/app.bsky.feed.generator/{rkey}")),
            pinned,
        }
    }

    #[test]
    fn preferences_read() {
        let v2 = json!({ "preferences": [
            { "$type": "app.bsky.actor.defs#adultContentPref", "enabled": false },
            { "$type": SAVED_V2, "items": [
                { "id": "1", "type": "timeline", "value": "following", "pinned": true },
                { "id": "2", "type": "feed", "value": "at://did:plc:x/app.bsky.feed.generator/for-you", "pinned": true },
                { "id": "3", "type": "list", "value": "at://did:plc:x/app.bsky.graph.list/l", "pinned": true },
                { "id": "4", "type": "feed", "value": "at://did:plc:x/app.bsky.feed.generator/art", "pinned": false },
                { "id": "5", "type": "feed", "value": "not a uri", "pinned": false } ] },
            { "$type": SAVED_V1, "pinned": ["at://did:plc:x/app.bsky.feed.generator/old"], "saved": [] } ] });
        assert_eq!(
            saved_of(&v2),
            [
                SavedFeed {
                    name: "Following".into(),
                    uri: None,
                    pinned: true
                },
                feed("", "for-you", true),
                feed("", "art", false),
            ]
        );
        let v1 = json!({ "preferences": [{ "$type": SAVED_V1,
            "pinned": ["at://did:plc:x/app.bsky.feed.generator/a", "at://did:plc:x/app.bsky.graph.list/l"],
            "saved": ["at://did:plc:x/app.bsky.feed.generator/b", "at://did:plc:x/app.bsky.feed.generator/a"] }] });
        assert_eq!(saved_of(&v1), [feed("", "a", true), feed("", "b", false)]);
        assert!(saved_of(&json!({ "preferences": [] })).is_empty());
        assert_eq!(
            fallback_name("at://did:plc:x/app.bsky.feed.generator/art"),
            "art"
        );
    }

    #[test]
    fn names_matched() {
        let saved = [
            SavedFeed {
                name: "Following".into(),
                uri: None,
                pinned: true,
            },
            feed("For You", "for-you", true),
            feed("Discover", "whats-hot", false),
            feed("Cat Pics", "cats", false),
            feed("Dog Pics", "dogs", true),
        ];
        let uri = |r: &str| format!("at://did:plc:x/app.bsky.feed.generator/{r}");
        assert_eq!(match_name(&saved, "  for you ").unwrap(), uri("for-you"));
        assert_eq!(match_name(&saved, "DISCO").unwrap(), uri("whats-hot"));
        assert_eq!(match_name(&saved, "cat").unwrap(), uri("cats"));
        assert_eq!(
            match_name(&saved, "pics").unwrap_err(),
            "\"pics\" names several saved feeds (Cat Pics, Dog Pics). Your feeds: Following, For You, Dog Pics, Discover, Cat Pics"
        );
        assert_eq!(
            match_name(&saved, "News").unwrap_err(),
            "No saved feed is named \"News\". Your feeds: Following, For You, Dog Pics, Discover, Cat Pics"
        );
        // An exact name wins over one that holds it.
        let both = [
            feed("Art", "art", false),
            feed("Art History", "history", false),
        ];
        assert_eq!(match_name(&both, "art").unwrap(), uri("art"));
        assert_eq!(
            match_name(&[], "x").unwrap_err(),
            "No saved feed is named \"x\". You have no saved feeds"
        );
    }
}