use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::time::Duration;
use crate::error::SkybaseError;
pub const DEFAULT_APPVIEW_ENDPOINT: &str = "https://public.api.bsky.app";
pub const DEFAULT_CDN_ENDPOINT: &str = "https://cdn.bsky.app";
pub const DEFAULT_APPVIEW_TIMEOUT_MS: u64 = 1500;
pub const DEFAULT_MAX_PAGES: usize = 100;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActorProfile {
#[serde(default)]
pub did: Option<String>,
pub handle: Option<String>,
#[serde(alias = "display_name")]
pub display_name: Option<String>,
#[serde(default)]
pub avatar: Option<String>,
pub description: Option<String>,
#[serde(alias = "followers_count")]
pub followers_count: Option<u64>,
#[serde(alias = "follows_count")]
pub follows_count: Option<u64>,
#[serde(alias = "created_at")]
pub created_at: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct ActorSuggestion {
pub did: String,
pub handle: String,
#[serde(default, rename = "displayName")]
pub display_name: Option<String>,
#[serde(default)]
pub avatar: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct PostView {
pub author_did: String,
pub text: String,
pub cid: Option<String>,
}
#[derive(Debug, Clone)]
pub struct AppViewClient {
appview_url: String,
cdn_url: String,
http_client: reqwest::Client,
}
impl Default for AppViewClient {
fn default() -> Self {
Self::new()
}
}
impl AppViewClient {
#[must_use]
pub fn new() -> Self {
Self::with_endpoints(DEFAULT_APPVIEW_ENDPOINT, DEFAULT_CDN_ENDPOINT)
}
#[must_use]
pub fn with_endpoint(endpoint: impl Into<String>) -> Self {
Self::with_endpoints(endpoint, DEFAULT_CDN_ENDPOINT)
}
#[must_use]
pub fn with_endpoints(
appview_endpoint: impl Into<String>,
cdn_endpoint: impl Into<String>,
) -> Self {
let client = reqwest::Client::builder()
.use_rustls_tls()
.timeout(Duration::from_millis(DEFAULT_APPVIEW_TIMEOUT_MS))
.build()
.unwrap_or_else(|_| {
reqwest::Client::builder()
.timeout(Duration::from_millis(DEFAULT_APPVIEW_TIMEOUT_MS))
.build()
.unwrap_or_default()
});
Self {
appview_url: appview_endpoint.into().trim_end_matches('/').to_string(),
cdn_url: cdn_endpoint.into().trim_end_matches('/').to_string(),
http_client: client,
}
}
#[must_use]
pub fn appview_url(&self) -> &str {
&self.appview_url
}
#[must_use]
pub fn cdn_url(&self) -> &str {
&self.cdn_url
}
#[must_use]
pub fn http_client(&self) -> &reqwest::Client {
&self.http_client
}
pub async fn get<T: DeserializeOwned>(
&self,
endpoint: &str,
query: &[(&str, String)],
) -> Result<T, SkybaseError> {
let url = format!("{}/xrpc/{endpoint}", self.appview_url);
let resp = self.http_client.get(&url).query(query).send().await?;
if !resp.status().is_success() {
return Err(SkybaseError::Internal(format!(
"AppView {endpoint} returned HTTP {}",
resp.status()
)));
}
let body = resp.json::<T>().await?;
Ok(body)
}
pub async fn paginate<T, I, F>(
&self,
endpoint: &str,
base_query: &[(&str, String)],
page_limit: u8,
extract: F,
) -> Vec<I>
where
T: DeserializeOwned,
F: Fn(T) -> (Vec<I>, Option<String>),
{
let page_limit = page_limit.clamp(1, 100).to_string();
let mut items = Vec::new();
let mut cursor: Option<String> = None;
for _ in 0..DEFAULT_MAX_PAGES {
let mut query: Vec<(&str, String)> = base_query.to_vec();
query.push(("limit", page_limit.clone()));
if let Some(ref c) = cursor {
query.push(("cursor", c.clone()));
}
let body: T = match self.get(endpoint, &query).await {
Ok(body) => body,
Err(_) => break,
};
let (page, next_cursor) = extract(body);
let count = page.len();
items.extend(page);
if count == 0
|| next_cursor.as_deref().is_none_or(str::is_empty)
|| next_cursor == cursor
{
break;
}
cursor = next_cursor;
}
items
}
pub async fn resolve_handle(&self, handle: &str) -> Option<String> {
let clean = handle.trim().trim_start_matches('@');
if clean.starts_with("did:") {
return Some(clean.to_string());
}
let normalized =
skyauth::identity::normalize_user_handle(clean).unwrap_or_else(|_| clean.to_string());
#[derive(Deserialize)]
struct ResolveHandleResponse {
did: String,
}
self.get::<ResolveHandleResponse>(
"com.atproto.identity.resolveHandle",
&[("handle", normalized)],
)
.await
.ok()
.map(|r| r.did)
}
pub async fn search_actors_typeahead(&self, query: &str, limit: u8) -> Vec<ActorSuggestion> {
let clean = query.trim().trim_start_matches('@').trim();
if clean.is_empty() {
return Vec::new();
}
let clamped_limit = limit.clamp(1, 25).to_string();
#[derive(Deserialize)]
struct TypeaheadResponse {
#[serde(default)]
actors: Vec<ActorSuggestion>,
}
self.get::<TypeaheadResponse>(
"app.bsky.actor.searchActorsTypeahead",
&[("q", clean.to_string()), ("limit", clamped_limit)],
)
.await
.map(|r| r.actors)
.unwrap_or_default()
}
pub async fn fetch_profile(&self, did: &str) -> Option<ActorProfile> {
#[derive(Deserialize)]
struct RawProfile {
did: Option<String>,
handle: Option<String>,
#[serde(rename = "displayName")]
display_name: Option<String>,
avatar: Option<String>,
description: Option<String>,
#[serde(rename = "followersCount")]
followers_count: Option<u64>,
#[serde(rename = "followsCount")]
follows_count: Option<u64>,
#[serde(rename = "createdAt")]
created_at: Option<String>,
}
let raw: RawProfile = self
.get("app.bsky.actor.getProfile", &[("actor", did.to_string())])
.await
.ok()?;
Some(ActorProfile {
did: raw.did,
handle: raw.handle,
display_name: raw.display_name,
avatar: raw.avatar,
description: raw.description,
followers_count: raw.followers_count,
follows_count: raw.follows_count,
created_at: raw.created_at,
})
}
pub async fn fetch_post(&self, uri: &str) -> Option<PostView> {
#[derive(Deserialize)]
struct RawRecord {
text: Option<String>,
}
#[derive(Deserialize)]
struct RawAuthor {
did: String,
}
#[derive(Deserialize)]
struct RawPostView {
author: RawAuthor,
record: serde_json::Value,
cid: Option<String>,
}
#[derive(Deserialize)]
struct RawPostsResponse {
posts: Vec<RawPostView>,
}
let raw: RawPostsResponse = self
.get("app.bsky.feed.getPosts", &[("uris", uri.to_string())])
.await
.ok()?;
let first = raw.posts.into_iter().next()?;
let text = serde_json::from_value::<RawRecord>(first.record)
.ok()
.and_then(|r| r.text)
.unwrap_or_default();
Some(PostView {
author_did: first.author.did,
text,
cid: first.cid,
})
}
pub async fn fetch_follows(&self, actor: &str, limit: u8) -> Vec<String> {
#[derive(Deserialize)]
struct FollowProfile {
did: String,
}
#[derive(Deserialize)]
struct GetFollowsResponse {
follows: Vec<FollowProfile>,
cursor: Option<String>,
}
self.paginate::<GetFollowsResponse, _, _>(
"app.bsky.graph.getFollows",
&[("actor", actor.to_string())],
limit,
|body| {
(
body.follows.into_iter().map(|f| f.did).collect(),
body.cursor,
)
},
)
.await
}
pub async fn fetch_followers(&self, actor: &str, limit: u8) -> Vec<String> {
#[derive(Deserialize)]
struct FollowerProfile {
did: String,
}
#[derive(Deserialize)]
struct GetFollowersResponse {
followers: Vec<FollowerProfile>,
cursor: Option<String>,
}
self.paginate::<GetFollowersResponse, _, _>(
"app.bsky.graph.getFollowers",
&[("actor", actor.to_string())],
limit,
|body| {
(
body.followers.into_iter().map(|f| f.did).collect(),
body.cursor,
)
},
)
.await
}
pub async fn fetch_follow_records(&self, actor: &str, limit: u8) -> Vec<(String, String)> {
#[derive(Deserialize)]
struct FollowValue {
subject: Option<String>,
}
#[derive(Deserialize)]
struct RecordItem {
uri: String,
value: FollowValue,
}
#[derive(Deserialize)]
struct ListRecordsResp {
records: Vec<RecordItem>,
cursor: Option<String>,
}
self.paginate::<ListRecordsResp, _, _>(
"com.atproto.repo.listRecords",
&[
("repo", actor.to_string()),
("collection", "app.bsky.graph.follow".to_string()),
],
limit,
|body| {
let mut items = Vec::new();
for rec in body.records {
if let Some(subject) = rec.value.subject {
let rkey = rec.uri.rsplit('/').next().unwrap_or_default().to_string();
if !rkey.is_empty() && !subject.is_empty() {
items.push((rkey, subject));
}
}
}
(items, body.cursor)
},
)
.await
}
#[must_use]
pub fn thumbnail_url(&self, author_did: &str, cid: &str) -> String {
format!(
"{}/img/feed_thumbnail/plain/{author_did}/{cid}@jpeg",
self.cdn_url
)
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod tests {
use super::*;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
#[tokio::test]
async fn test_appview_client_methods_and_wiremock_queries() {
let default_client = AppViewClient::default();
assert_eq!(default_client.appview_url(), DEFAULT_APPVIEW_ENDPOINT);
assert_eq!(default_client.cdn_url(), DEFAULT_CDN_ENDPOINT);
let _ = default_client.http_client();
assert_eq!(
default_client.thumbnail_url("did:plc:alice", "bafy123"),
"https://cdn.bsky.app/img/feed_thumbnail/plain/did:plc:alice/bafy123@jpeg"
);
let server = MockServer::start().await;
let client = AppViewClient::with_endpoint(server.uri());
assert_eq!(
client.resolve_handle("@did:plc:alice123").await.as_deref(),
Some("did:plc:alice123")
);
Mock::given(method("GET"))
.and(path("/xrpc/com.atproto.identity.resolveHandle"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(serde_json::json!({"did": "did:plc:alice123"})),
)
.mount(&server)
.await;
assert_eq!(
client.resolve_handle("@alice").await.as_deref(),
Some("did:plc:alice123")
);
assert!(client.search_actors_typeahead(" @ ", 10).await.is_empty());
Mock::given(method("GET"))
.and(path("/xrpc/app.bsky.actor.searchActorsTypeahead"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"actors": [{"did": "did:plc:alice123", "handle": "alice.bsky.social", "displayName": "Alice"}]
})))
.mount(&server)
.await;
let suggestions = client.search_actors_typeahead("alice", 5).await;
assert_eq!(suggestions.len(), 1);
assert_eq!(suggestions[0].did, "did:plc:alice123");
Mock::given(method("GET"))
.and(path("/xrpc/app.bsky.actor.getProfile"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"did": "did:plc:alice123",
"handle": "alice.bsky.social",
"displayName": "Alice",
"followersCount": 100,
"followsCount": 50
})))
.mount(&server)
.await;
let prof = client.fetch_profile("did:plc:alice123").await.unwrap();
assert_eq!(prof.handle.as_deref(), Some("alice.bsky.social"));
assert_eq!(prof.display_name.as_deref(), Some("Alice"));
assert_eq!(prof.followers_count, Some(100));
assert_eq!(prof.follows_count, Some(50));
Mock::given(method("GET"))
.and(path("/xrpc/app.bsky.feed.getPosts"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"posts": [{
"author": {"did": "did:plc:alice123"},
"record": {"text": "post body"},
"cid": "bafypost"
}]
})))
.mount(&server)
.await;
let post = client
.fetch_post("at://did:plc:alice123/app.bsky.feed.post/1")
.await
.unwrap();
assert_eq!(post.text, "post body");
Mock::given(method("GET"))
.and(path("/xrpc/app.bsky.graph.getFollows"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"follows": [{"did": "did:plc:f1"}]
})))
.mount(&server)
.await;
assert_eq!(
client.fetch_follows("did:plc:alice123", 10).await,
vec!["did:plc:f1"]
);
Mock::given(method("GET"))
.and(path("/xrpc/app.bsky.graph.getFollowers"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"followers": [{"did": "did:plc:fl1"}]
})))
.mount(&server)
.await;
assert_eq!(
client.fetch_followers("did:plc:alice123", 10).await,
vec!["did:plc:fl1"]
);
Mock::given(method("GET"))
.and(path("/xrpc/com.atproto.repo.listRecords"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"records": [{
"uri": "at://did:plc:alice123/app.bsky.graph.follow/rkey1",
"value": {"subject": "did:plc:f1"}
}]
})))
.mount(&server)
.await;
assert_eq!(
client.fetch_follow_records("did:plc:alice123", 10).await,
vec![("rkey1".to_string(), "did:plc:f1".to_string())]
);
}
}