use std::sync::Arc;
use std::time::Duration;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use serde::Deserialize;
use tokio::sync::RwLock;
use tracing::{debug, error, info, warn};
use crate::chat::types::{
AcceptConvoRequest, AcceptConvoResponse, ConvoView, GetMessagesResponse,
ListConvoRequestsResponse, ListConvosResponse, MessageView, SendMessagePayload,
SendMessageRequest, UpdateReadRequest,
};
use crate::error::SkybaseError;
pub const DEFAULT_CHAT_ENDPOINT: &str = "https://api.bsky.chat";
pub const ATPROTO_CHAT_PROXY_DID: &str = "did:web:api.bsky.chat#bsky_chat";
#[derive(Debug, Deserialize)]
struct CreateSessionResponse {
did: String,
#[serde(rename = "accessJwt")]
access_jwt: String,
#[serde(rename = "refreshJwt", default)]
refresh_jwt: Option<String>,
}
#[derive(Debug, Deserialize)]
struct RefreshSessionResponse {
#[serde(rename = "accessJwt")]
access_jwt: String,
#[serde(rename = "refreshJwt", default)]
refresh_jwt: Option<String>,
}
#[derive(Debug, Clone)]
struct BotCredentials {
pds_endpoint: String,
identifier: String,
password: String,
}
#[derive(Debug, Clone)]
struct AuthState {
access_jwt: String,
refresh_jwt: Option<String>,
credentials: Option<BotCredentials>,
}
#[derive(Clone)]
pub struct ChatClient {
base_url: String,
client: reqwest::Client,
auth_state: Arc<RwLock<AuthState>>,
}
impl ChatClient {
pub fn new(
base_url: impl Into<String>,
access_token: impl Into<String>,
) -> Result<Self, SkybaseError> {
let base_url = base_url.into().trim_end_matches('/').to_string();
let token = access_token.into();
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
if !base_url.contains("api.bsky.chat") {
headers.insert(
HeaderName::from_static("atproto-proxy"),
HeaderValue::from_static(ATPROTO_CHAT_PROXY_DID),
);
}
let client = reqwest::Client::builder()
.default_headers(headers)
.timeout(Duration::from_secs(10))
.build()
.map_err(|e| SkybaseError::Chat(format!("Failed to build chat HTTP client: {e}")))?;
let auth_state = Arc::new(RwLock::new(AuthState {
access_jwt: token,
refresh_jwt: None,
credentials: None,
}));
Ok(Self {
base_url,
client,
auth_state,
})
}
#[must_use]
pub fn with_refresh_token(self, refresh_jwt: impl Into<String>) -> Self {
let token = refresh_jwt.into();
if !token.trim().is_empty() {
if let Ok(mut state) = self.auth_state.try_write() {
state.refresh_jwt = Some(token);
}
}
self
}
#[must_use]
pub fn with_credentials(
self,
pds_endpoint: impl Into<String>,
identifier: impl Into<String>,
password: impl Into<String>,
) -> Self {
if let Ok(mut state) = self.auth_state.try_write() {
state.credentials = Some(BotCredentials {
pds_endpoint: pds_endpoint.into().trim_end_matches('/').to_string(),
identifier: identifier.into(),
password: password.into(),
});
}
self
}
pub async fn current_access_token(&self) -> String {
self.auth_state.read().await.access_jwt.clone()
}
pub async fn login_with_app_password(
pds_endpoint: &str,
chat_endpoint: &str,
identifier: &str,
password: &str,
) -> Result<(Self, String), SkybaseError> {
let pds_url = pds_endpoint.trim_end_matches('/');
let login_url = format!("{pds_url}/xrpc/com.atproto.server.createSession");
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(15))
.build()
.map_err(|e| SkybaseError::Chat(format!("Failed to build login HTTP client: {e}")))?;
let body = serde_json::json!({
"identifier": identifier,
"password": password,
});
let resp = http
.post(&login_url)
.json(&body)
.send()
.await
.map_err(|e| SkybaseError::Chat(format!("createSession request failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
let err_body = resp.text().await.unwrap_or_default();
return Err(SkybaseError::Chat(format!(
"Failed to authenticate bot account ({identifier}) at {pds_url} (HTTP {status}): {err_body}"
)));
}
let session: CreateSessionResponse = resp.json().await.map_err(|e| {
SkybaseError::Chat(format!("Failed to parse createSession response: {e}"))
})?;
let mut chat_client = Self::new(chat_endpoint, &session.access_jwt)?;
if let Some(ref refresh) = session.refresh_jwt {
chat_client = chat_client.with_refresh_token(refresh);
}
chat_client = chat_client.with_credentials(pds_url, identifier, password);
Ok((chat_client, session.did))
}
async fn can_refresh(&self) -> bool {
let state = self.auth_state.read().await;
state.refresh_jwt.is_some() || state.credentials.is_some()
}
async fn refresh_session_or_relogin(&self, failed_token: &str) -> Result<(), SkybaseError> {
let mut state = self.auth_state.write().await;
if state.access_jwt != failed_token {
debug!("ATProto chat session token was already refreshed by another task");
return Ok(());
}
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(15))
.build()
.map_err(|e| SkybaseError::Chat(format!("Failed to build refresh HTTP client: {e}")))?;
if let (Some(ref refresh_jwt), Some(ref creds)) = (&state.refresh_jwt, &state.credentials) {
let refresh_url = format!(
"{}/xrpc/com.atproto.server.refreshSession",
creds.pds_endpoint.trim_end_matches('/')
);
match http
.post(&refresh_url)
.header(AUTHORIZATION, format!("Bearer {refresh_jwt}"))
.send()
.await
{
Ok(resp) if resp.status().is_success() => {
match resp.json::<RefreshSessionResponse>().await {
Ok(refreshed) => {
info!("Successfully refreshed ATProto chat session token via refreshSession");
state.access_jwt = refreshed.access_jwt;
if let Some(new_refresh) = refreshed.refresh_jwt {
if !new_refresh.trim().is_empty() {
state.refresh_jwt = Some(new_refresh);
}
}
return Ok(());
}
Err(e) => {
warn!(
error = %e,
"Failed to parse refreshSession response; falling back to full re-login"
);
}
}
}
Ok(resp) => {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
warn!(
status = %status,
body = %body,
"refreshSession failed; falling back to full re-login"
);
}
Err(e) => {
warn!(
error = %e,
"Network error during refreshSession; falling back to full re-login"
);
}
}
}
if let Some(ref creds) = state.credentials {
info!(
identifier = %creds.identifier,
"Re-authenticating ATProto chat session via App Password..."
);
let login_url = format!(
"{}/xrpc/com.atproto.server.createSession",
creds.pds_endpoint.trim_end_matches('/')
);
let body = serde_json::json!({
"identifier": creds.identifier,
"password": creds.password,
});
let resp = http
.post(&login_url)
.json(&body)
.send()
.await
.map_err(|e| SkybaseError::Chat(format!("Re-login request failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
let err_body = resp.text().await.unwrap_or_default();
return Err(SkybaseError::Chat(format!(
"Failed to re-authenticate bot session at {login_url} (HTTP {status}): {err_body}"
)));
}
let session: CreateSessionResponse = resp.json().await.map_err(|e| {
SkybaseError::Chat(format!("Failed to parse createSession response: {e}"))
})?;
info!("Successfully re-authenticated ATProto chat session via App Password");
state.access_jwt = session.access_jwt;
if let Some(new_refresh) = session.refresh_jwt {
if !new_refresh.trim().is_empty() {
state.refresh_jwt = Some(new_refresh);
}
}
return Ok(());
}
Err(SkybaseError::Chat(
"Session token expired, but no refresh token or credentials configured to refresh"
.to_string(),
))
}
async fn send_request(
&self,
op_name: &str,
method: reqwest::Method,
url: &str,
body: Option<serde_json::Value>,
) -> Result<reqwest::Response, SkybaseError> {
let current_token = self.auth_state.read().await.access_jwt.clone();
let req = self.build_request(method.clone(), url, ¤t_token, body.as_ref());
let resp = req
.send()
.await
.map_err(|e| SkybaseError::Chat(format!("{op_name} request failed: {e}")))?;
let status = resp.status();
if status.is_success() {
return Ok(resp);
}
let body_text = resp.text().await.unwrap_or_default();
let is_token_expired = status == reqwest::StatusCode::UNAUTHORIZED
|| (status == reqwest::StatusCode::BAD_REQUEST && body_text.contains("ExpiredToken"));
if is_token_expired && self.can_refresh().await {
warn!(
op = op_name,
status = %status,
"ATProto chat session token expired; refreshing and retrying..."
);
if let Err(e) = self.refresh_session_or_relogin(¤t_token).await {
error!(error = %e, "Failed to refresh ATProto chat session");
return Err(SkybaseError::Chat(format!(
"{op_name} failed with status {status}: {body_text} (refresh failed: {e})"
)));
}
let new_token = self.auth_state.read().await.access_jwt.clone();
let retry_req = self.build_request(method, url, &new_token, body.as_ref());
let retry_resp = retry_req
.send()
.await
.map_err(|e| SkybaseError::Chat(format!("{op_name} retry failed: {e}")))?;
if !retry_resp.status().is_success() {
let retry_status = retry_resp.status();
let retry_body = retry_resp.text().await.unwrap_or_default();
return Err(SkybaseError::Chat(format!(
"{op_name} failed with status {retry_status}: {retry_body}"
)));
}
return Ok(retry_resp);
}
Err(SkybaseError::Chat(format!(
"{op_name} failed with status {status}: {body_text}"
)))
}
fn build_request(
&self,
method: reqwest::Method,
url: &str,
token: &str,
body: Option<&serde_json::Value>,
) -> reqwest::RequestBuilder {
let mut req = self
.client
.request(method, url)
.header(AUTHORIZATION, format!("Bearer {token}"));
if let Some(b) = body {
req = req.json(b);
}
req
}
pub async fn list_convos(
&self,
limit: Option<usize>,
cursor: Option<&str>,
) -> Result<ListConvosResponse, SkybaseError> {
let mut url = format!("{}/xrpc/chat.bsky.convo.listConvos", self.base_url);
let mut query_params = Vec::new();
if let Some(limit) = limit {
query_params.push(format!("limit={limit}"));
}
if let Some(cursor) = cursor {
query_params.push(format!("cursor={cursor}"));
}
if !query_params.is_empty() {
url.push('?');
url.push_str(&query_params.join("&"));
}
let resp = self
.send_request("listConvos", reqwest::Method::GET, &url, None)
.await?;
let result = resp
.json::<ListConvosResponse>()
.await
.map_err(|e| SkybaseError::Chat(format!("Failed to parse listConvos response: {e}")))?;
debug!(count = result.convos.len(), "Fetched chat conversations");
Ok(result)
}
pub async fn list_convo_requests(
&self,
limit: Option<usize>,
cursor: Option<&str>,
) -> Result<ListConvoRequestsResponse, SkybaseError> {
let mut url = format!("{}/xrpc/chat.bsky.convo.listConvoRequests", self.base_url);
let mut query_params = Vec::new();
if let Some(limit) = limit {
query_params.push(format!("limit={limit}"));
}
if let Some(cursor) = cursor {
query_params.push(format!("cursor={cursor}"));
}
if !query_params.is_empty() {
url.push('?');
url.push_str(&query_params.join("&"));
}
let resp = self
.send_request("listConvoRequests", reqwest::Method::GET, &url, None)
.await?;
let result = resp
.json::<ListConvoRequestsResponse>()
.await
.map_err(|e| {
SkybaseError::Chat(format!("Failed to parse listConvoRequests response: {e}"))
})?;
debug!(
count = result.requests.len(),
"Fetched chat conversation requests"
);
Ok(result)
}
pub async fn accept_convo(&self, convo_id: &str) -> Result<AcceptConvoResponse, SkybaseError> {
let url = format!("{}/xrpc/chat.bsky.convo.acceptConvo", self.base_url);
let req = AcceptConvoRequest {
convo_id: convo_id.to_string(),
};
let body = serde_json::to_value(&req)
.map_err(|e| SkybaseError::Chat(format!("Failed to serialize acceptConvo: {e}")))?;
let resp = self
.send_request("acceptConvo", reqwest::Method::POST, &url, Some(body))
.await?;
let result = resp.json::<AcceptConvoResponse>().await.map_err(|e| {
SkybaseError::Chat(format!("Failed to parse acceptConvo response: {e}"))
})?;
debug!(
convo_id = %convo_id,
rev = ?result.rev,
"Accepted chat conversation request"
);
Ok(result)
}
pub async fn get_messages(
&self,
convo_id: &str,
limit: Option<usize>,
cursor: Option<&str>,
) -> Result<GetMessagesResponse, SkybaseError> {
let mut url = format!(
"{}/xrpc/chat.bsky.convo.getMessages?convoId={convo_id}",
self.base_url
);
if let Some(limit) = limit {
url.push_str(&format!("&limit={limit}"));
}
if let Some(cursor) = cursor {
url.push_str(&format!("&cursor={cursor}"));
}
let resp = self
.send_request("getMessages", reqwest::Method::GET, &url, None)
.await?;
let result = resp.json::<GetMessagesResponse>().await.map_err(|e| {
SkybaseError::Chat(format!("Failed to parse getMessages response: {e}"))
})?;
Ok(result)
}
pub async fn send_message(
&self,
convo_id: &str,
text: &str,
) -> Result<MessageView, SkybaseError> {
let payload = SendMessagePayload::new(text);
self.send_message_payload(convo_id, payload).await
}
pub async fn send_message_payload(
&self,
convo_id: &str,
payload: SendMessagePayload,
) -> Result<MessageView, SkybaseError> {
let url = format!("{}/xrpc/chat.bsky.convo.sendMessage", self.base_url);
let req = SendMessageRequest {
convo_id: convo_id.to_string(),
message: payload,
};
let body = serde_json::to_value(&req)
.map_err(|e| SkybaseError::Chat(format!("Failed to serialize sendMessage: {e}")))?;
let resp = self
.send_request("sendMessage", reqwest::Method::POST, &url, Some(body))
.await?;
let result = resp.json::<MessageView>().await.map_err(|e| {
SkybaseError::Chat(format!("Failed to parse sendMessage response: {e}"))
})?;
Ok(result)
}
pub async fn update_read(&self, convo_id: &str, message_id: &str) -> Result<(), SkybaseError> {
let url = format!("{}/xrpc/chat.bsky.convo.updateRead", self.base_url);
let req = UpdateReadRequest {
convo_id: convo_id.to_string(),
message_id: message_id.to_string(),
};
let body = serde_json::to_value(&req)
.map_err(|e| SkybaseError::Chat(format!("Failed to serialize updateRead: {e}")))?;
self.send_request("updateRead", reqwest::Method::POST, &url, Some(body))
.await?;
Ok(())
}
pub async fn get_convo_for_members(&self, members: &[&str]) -> Result<ConvoView, SkybaseError> {
let mut url = format!("{}/xrpc/chat.bsky.convo.getConvoForMembers?", self.base_url);
let params: Vec<String> = members.iter().map(|m| format!("members={m}")).collect();
url.push_str(¶ms.join("&"));
let resp = self
.send_request("getConvoForMembers", reqwest::Method::GET, &url, None)
.await?;
#[derive(Deserialize)]
struct GetConvoResponse {
convo: ConvoView,
}
let result = resp.json::<GetConvoResponse>().await.map_err(|e| {
SkybaseError::Chat(format!("Failed to parse getConvoForMembers response: {e}"))
})?;
Ok(result.convo)
}
pub async fn find_or_create_convo_for_did(&self, did: &str) -> Result<String, SkybaseError> {
if let Ok(convo) = self.get_convo_for_members(&[did]).await {
return Ok(convo.id);
}
let resp = self.list_convos(Some(50), None).await?;
for convo in resp.convos {
if convo.members.iter().any(|m| m.did == did) {
return Ok(convo.id);
}
}
Err(SkybaseError::Chat(format!(
"Could not find or establish conversation with {did}"
)))
}
}
#[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_chat_client_login_and_endpoints_and_auto_refresh() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/xrpc/com.atproto.server.createSession"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"did": "did:plc:bot123",
"accessJwt": "tok_initial",
"refreshJwt": "ref_initial"
})))
.mount(&server)
.await;
let (client, bot_did) = ChatClient::login_with_app_password(
&server.uri(),
&server.uri(),
"bot.bsky.social",
"app-pass",
)
.await
.unwrap();
assert_eq!(bot_did, "did:plc:bot123");
assert_eq!(client.current_access_token().await, "tok_initial");
Mock::given(method("GET"))
.and(path("/xrpc/chat.bsky.convo.listConvos"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"convos": [{
"id": "convo-1",
"rev": "r1",
"members": [{"did": "did:plc:alice", "handle": "alice.bsky.social"}],
"unreadCount": 1
}],
"cursor": "c1"
})))
.mount(&server)
.await;
let convos = client.list_convos(Some(10), Some("c0")).await.unwrap();
assert_eq!(convos.convos.len(), 1);
Mock::given(method("GET"))
.and(path("/xrpc/chat.bsky.convo.listConvoRequests"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"requests": [{"id": "req-1", "rev": "r1", "members": [], "unreadCount": 0}],
"cursor": "rc1"
})))
.mount(&server)
.await;
let reqs = client
.list_convo_requests(Some(5), Some("rc0"))
.await
.unwrap();
assert_eq!(reqs.requests.len(), 1);
Mock::given(method("POST"))
.and(path("/xrpc/chat.bsky.convo.acceptConvo"))
.respond_with(
ResponseTemplate::new(200).set_body_json(serde_json::json!({"rev": "r2"})),
)
.mount(&server)
.await;
let accepted = client.accept_convo("req-1").await.unwrap();
assert_eq!(accepted.rev.as_deref(), Some("r2"));
Mock::given(method("GET"))
.and(path("/xrpc/chat.bsky.convo.getMessages"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"messages": [{
"$type": "chat.bsky.convo.defs#messageView",
"id": "m1",
"rev": "r1",
"text": "hello",
"sender": {"did": "did:plc:alice"},
"sentAt": "2026-11-03T00:00:00Z"
}]
})))
.mount(&server)
.await;
let msgs = client
.get_messages("convo-1", Some(10), Some("mc0"))
.await
.unwrap();
assert_eq!(msgs.messages.len(), 1);
Mock::given(method("POST"))
.and(path("/xrpc/chat.bsky.convo.sendMessage"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"id": "m2",
"rev": "r2",
"text": "reply https://example.com",
"sender": {"did": "did:plc:bot123"},
"sentAt": "2026-11-03T00:00:01Z"
})))
.mount(&server)
.await;
let sent = client
.send_message("convo-1", "reply https://example.com")
.await
.unwrap();
assert_eq!(sent.id, "m2");
Mock::given(method("POST"))
.and(path("/xrpc/chat.bsky.convo.updateRead"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.mount(&server)
.await;
client.update_read("convo-1", "m2").await.unwrap();
Mock::given(method("GET"))
.and(path("/xrpc/chat.bsky.convo.getConvoForMembers"))
.respond_with(ResponseTemplate::new(500).set_body_string("err"))
.mount(&server)
.await;
let found_id = client
.find_or_create_convo_for_did("did:plc:alice")
.await
.unwrap();
assert_eq!(found_id, "convo-1");
assert!(client
.find_or_create_convo_for_did("did:plc:unknown")
.await
.is_err());
Mock::given(method("POST"))
.and(path("/xrpc/com.atproto.server.refreshSession"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"accessJwt": "tok_refreshed",
"refreshJwt": "ref_rotated"
})))
.up_to_n_times(1)
.mount(&server)
.await;
client
.refresh_session_or_relogin("tok_initial")
.await
.unwrap();
assert_eq!(client.current_access_token().await, "tok_refreshed");
client
.refresh_session_or_relogin("tok_initial")
.await
.unwrap();
Mock::given(method("POST"))
.and(path("/xrpc/com.atproto.server.refreshSession"))
.respond_with(ResponseTemplate::new(400).set_body_string("ExpiredToken"))
.mount(&server)
.await;
client
.refresh_session_or_relogin("tok_refreshed")
.await
.unwrap();
assert_eq!(client.current_access_token().await, "tok_initial");
}
}