federation refinement
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
use activitypub_federation::{
|
||||
config::Data,
|
||||
fetch::object_id::ObjectId,
|
||||
kinds::activity::{AcceptType, CreateType, DeleteType, FollowType, RejectType, UndoType},
|
||||
traits::{Activity, Actor, Object},
|
||||
kinds::activity::{AcceptType, CreateType, DeleteType, FollowType, RejectType, UndoType, UpdateType},
|
||||
traits::{Activity, Object},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
@@ -11,7 +11,7 @@ use crate::actors::DbActor;
|
||||
use crate::data::FederationData;
|
||||
use crate::error::Error;
|
||||
use crate::objects::{DbReview, ReviewObject};
|
||||
use crate::repository::FollowerStatus;
|
||||
use crate::repository::{FollowerStatus, FollowingStatus};
|
||||
|
||||
// --- Follow ---
|
||||
|
||||
@@ -19,7 +19,7 @@ use crate::repository::FollowerStatus;
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FollowActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type")]
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: FollowType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: ObjectId<DbActor>,
|
||||
@@ -39,56 +39,36 @@ impl Activity for FollowActivity {
|
||||
}
|
||||
|
||||
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
// Verify the target is a local actor
|
||||
let target_url = self.object.inner();
|
||||
if target_url.domain() != Some(&data.domain) {
|
||||
return Err(Error(anyhow::anyhow!(
|
||||
"follow target is not a local actor"
|
||||
)));
|
||||
// Url::domain() strips the port, so build host:port explicitly
|
||||
let target_domain = match (target_url.host_str(), target_url.port()) {
|
||||
(Some(host), Some(port)) => format!("{}:{}", host, port),
|
||||
(Some(host), None) => host.to_string(),
|
||||
_ => return Err(Error::bad_request(anyhow::anyhow!("invalid follow target URL"))),
|
||||
};
|
||||
if target_domain != data.domain {
|
||||
return Err(Error::bad_request(anyhow::anyhow!("follow target is not a local actor")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
let follower = self.actor.dereference(data).await?;
|
||||
let _follower = self.actor.dereference(data).await?;
|
||||
let local_actor = self.object.dereference(data).await?;
|
||||
|
||||
data.federation_repo
|
||||
.add_follower(
|
||||
local_actor.user_id.clone(),
|
||||
self.actor.inner().as_str(),
|
||||
FollowerStatus::Accepted,
|
||||
FollowerStatus::Pending,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Send Accept back
|
||||
let accept_id =
|
||||
Url::parse(&format!("{}/activities/{}", data.base_url, uuid::Uuid::new_v4()))
|
||||
.expect("valid url");
|
||||
let accept = AcceptActivity {
|
||||
id: accept_id,
|
||||
kind: Default::default(),
|
||||
actor: self.object.clone(),
|
||||
object: self.clone(),
|
||||
};
|
||||
|
||||
use activitypub_federation::activity_sending::SendActivityTask;
|
||||
use activitypub_federation::protocol::context::WithContext;
|
||||
|
||||
let accept_with_ctx = WithContext::new_default(accept);
|
||||
let sends =
|
||||
SendActivityTask::prepare(&accept_with_ctx, &local_actor, vec![follower.inbox()], data)
|
||||
.await?;
|
||||
for send in sends {
|
||||
send.sign_and_send(data).await?;
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
follower = %self.actor.inner(),
|
||||
local_user = %local_actor.user_id.value(),
|
||||
"accepted follow"
|
||||
"follow request pending approval"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -99,7 +79,7 @@ impl Activity for FollowActivity {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AcceptActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type")]
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: AcceptType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: FollowActivity,
|
||||
@@ -122,10 +102,17 @@ impl Activity for AcceptActivity {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
let remote_actor_url = self.actor.into_inner().to_string();
|
||||
tracing::info!(remote_actor_url = %remote_actor_url, "Follow accepted by remote instance");
|
||||
// TODO(ap): update ap_following to track accepted status
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
let local_user_id = crate::urls::extract_user_id_from_url(self.object.actor.inner())
|
||||
.ok_or_else(|| Error::bad_request(anyhow::anyhow!("invalid actor URL in Follow")))?;
|
||||
let remote_actor_url = self.actor.inner().as_str();
|
||||
data.federation_repo
|
||||
.update_following_status(local_user_id, remote_actor_url, FollowingStatus::Accepted)
|
||||
.await?;
|
||||
tracing::info!(
|
||||
remote_actor = %self.actor.inner(),
|
||||
"follow accepted by remote"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -136,7 +123,7 @@ impl Activity for AcceptActivity {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RejectActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type")]
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: RejectType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: FollowActivity,
|
||||
@@ -162,14 +149,10 @@ impl Activity for RejectActivity {
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
// The actor rejected our follow. Extract the local user from the original Follow's actor.
|
||||
let local_user_url = self.object.actor.inner();
|
||||
let path = local_user_url.path();
|
||||
if let Some(uid_str) = path.strip_prefix("/users/").and_then(|s| s.split('/').next()) {
|
||||
if let Ok(uuid) = uuid::Uuid::parse_str(uid_str) {
|
||||
let user_id = domain::value_objects::UserId::from_uuid(uuid);
|
||||
data.federation_repo
|
||||
.remove_following(user_id, self.actor.inner().as_str())
|
||||
.await?;
|
||||
}
|
||||
if let Some(user_id) = crate::urls::extract_user_id_from_url(local_user_url) {
|
||||
data.federation_repo
|
||||
.remove_following(user_id, self.actor.inner().as_str())
|
||||
.await?;
|
||||
}
|
||||
tracing::info!(actor = %self.actor.inner(), "follow rejected");
|
||||
Ok(())
|
||||
@@ -182,7 +165,7 @@ impl Activity for RejectActivity {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UndoActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type")]
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: UndoType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: FollowActivity,
|
||||
@@ -208,14 +191,10 @@ impl Activity for UndoActivity {
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
// Remote actor is unfollowing a local user
|
||||
let local_user_url = self.object.object.inner();
|
||||
let path = local_user_url.path();
|
||||
if let Some(uid_str) = path.strip_prefix("/users/").and_then(|s| s.split('/').next()) {
|
||||
if let Ok(uuid) = uuid::Uuid::parse_str(uid_str) {
|
||||
let user_id = domain::value_objects::UserId::from_uuid(uuid);
|
||||
data.federation_repo
|
||||
.remove_follower(user_id, self.actor.inner().as_str())
|
||||
.await?;
|
||||
}
|
||||
if let Some(user_id) = crate::urls::extract_user_id_from_url(local_user_url) {
|
||||
data.federation_repo
|
||||
.remove_follower(user_id, self.actor.inner().as_str())
|
||||
.await?;
|
||||
}
|
||||
tracing::info!(actor = %self.actor.inner(), "unfollowed");
|
||||
Ok(())
|
||||
@@ -228,7 +207,7 @@ impl Activity for UndoActivity {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CreateActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type")]
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: CreateType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: ReviewObject,
|
||||
@@ -248,6 +227,11 @@ impl Activity for CreateActivity {
|
||||
}
|
||||
|
||||
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
if self.object.attributed_to.inner() != self.actor.inner() {
|
||||
return Err(Error::bad_request(anyhow::anyhow!(
|
||||
"activity actor does not match object attributed_to"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -264,7 +248,7 @@ impl Activity for CreateActivity {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeleteActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type")]
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: DeleteType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: Url,
|
||||
@@ -287,8 +271,61 @@ impl Activity for DeleteActivity {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
tracing::info!(actor = %self.actor.inner(), object = %self.object, "delete received (no-op)");
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
data.federation_repo
|
||||
.delete_remote_review_by_ap_id(
|
||||
self.object.as_str(),
|
||||
self.actor.inner().as_str(),
|
||||
)
|
||||
.await?;
|
||||
tracing::info!(object = %self.object, "remote review deleted");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- Update ---
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UpdateActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: UpdateType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: ReviewObject,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Activity for UpdateActivity {
|
||||
type DataType = FederationData;
|
||||
type Error = Error;
|
||||
|
||||
fn id(&self) -> &Url {
|
||||
&self.id
|
||||
}
|
||||
|
||||
fn actor(&self) -> &Url {
|
||||
self.actor.inner()
|
||||
}
|
||||
|
||||
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
if self.object.attributed_to.inner() != self.actor.inner() {
|
||||
return Err(Error::bad_request(anyhow::anyhow!(
|
||||
"update actor does not match object attributed_to"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
let ap_id = self.object.id.inner().as_str();
|
||||
let rating = self.object.rating.min(5);
|
||||
let comment = self.object.comment.as_deref();
|
||||
let watched_at = self.object.watched_at.naive_utc();
|
||||
data.federation_repo
|
||||
.update_remote_review(ap_id, self.actor.inner().as_str(), rating, comment, watched_at)
|
||||
.await?;
|
||||
tracing::info!(actor = %self.actor.inner(), ap_id = %ap_id, "remote review updated");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -311,4 +348,6 @@ pub enum InboxActivities {
|
||||
Create(CreateActivity),
|
||||
#[serde(rename = "Delete")]
|
||||
Delete(DeleteActivity),
|
||||
#[serde(rename = "Update")]
|
||||
Update(UpdateActivity),
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ pub async fn actor_handler(
|
||||
data: Data<FederationData>,
|
||||
) -> Result<FederationJson<WithContext<Person>>, Error> {
|
||||
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||
.map_err(|_| Error(anyhow::anyhow!("invalid user id")))?;
|
||||
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||
let user_id = UserId::from_uuid(uuid);
|
||||
|
||||
let db_actor = get_local_actor(user_id, &data).await?;
|
||||
|
||||
@@ -19,7 +19,7 @@ use crate::repository::RemoteActor;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DbActor {
|
||||
pub user_id: UserId,
|
||||
pub email: String,
|
||||
pub username: String,
|
||||
pub public_key_pem: String,
|
||||
pub private_key_pem: Option<String>,
|
||||
pub inbox_url: Url,
|
||||
@@ -45,10 +45,6 @@ pub struct Person {
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
pub fn actor_url(base_url: &str, user_id: &UserId) -> Url {
|
||||
Url::parse(&format!("{}/users/{}", base_url, user_id.value())).expect("valid actor url")
|
||||
}
|
||||
|
||||
pub async fn get_local_actor(
|
||||
user_id: UserId,
|
||||
data: &Data<FederationData>,
|
||||
@@ -57,8 +53,8 @@ pub async fn get_local_actor(
|
||||
.user_repo
|
||||
.find_by_id(&user_id)
|
||||
.await
|
||||
.map_err(|e| Error(e.into()))?
|
||||
.ok_or_else(|| Error(anyhow::anyhow!("user not found: {}", user_id.value())))?;
|
||||
.map_err(Error::from)?
|
||||
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found: {}", user_id.value())))?;
|
||||
|
||||
let (public_key, private_key) = match data
|
||||
.federation_repo
|
||||
@@ -79,7 +75,7 @@ pub async fn get_local_actor(
|
||||
}
|
||||
};
|
||||
|
||||
let ap_id = actor_url(&data.base_url, user.id());
|
||||
let ap_id = crate::urls::actor_url(&data.base_url, user.id());
|
||||
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid inbox url");
|
||||
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid outbox url");
|
||||
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid followers url");
|
||||
@@ -87,7 +83,7 @@ pub async fn get_local_actor(
|
||||
|
||||
Ok(DbActor {
|
||||
user_id: user.id().clone(),
|
||||
email: user.email().value().to_string(),
|
||||
username: user.username().value().to_string(),
|
||||
public_key_pem: public_key,
|
||||
private_key_pem: Some(private_key),
|
||||
inbox_url,
|
||||
@@ -118,22 +114,10 @@ impl Object for DbActor {
|
||||
data: &Data<Self::DataType>,
|
||||
) -> Result<Option<Self>, Self::Error> {
|
||||
// Extract user_id from URL path: /users/{uuid}
|
||||
let path = object_id.path();
|
||||
let user_id_str = path
|
||||
.strip_prefix("/users/")
|
||||
.and_then(|s| s.split('/').next());
|
||||
|
||||
let user_id_str = match user_id_str {
|
||||
Some(s) => s,
|
||||
let user_id = match crate::urls::extract_user_id_from_url(&object_id) {
|
||||
Some(id) => id,
|
||||
None => return Ok(None),
|
||||
};
|
||||
|
||||
let uuid = match uuid::Uuid::parse_str(user_id_str) {
|
||||
Ok(u) => u,
|
||||
Err(_) => return Ok(None),
|
||||
};
|
||||
|
||||
let user_id = UserId::from_uuid(uuid);
|
||||
let user = match data.user_repo.find_by_id(&user_id).await {
|
||||
Ok(Some(u)) => u,
|
||||
_ => return Ok(None),
|
||||
@@ -149,7 +133,7 @@ impl Object for DbActor {
|
||||
None => return Ok(None),
|
||||
};
|
||||
|
||||
let ap_id = actor_url(&data.base_url, user.id());
|
||||
let ap_id = crate::urls::actor_url(&data.base_url, user.id());
|
||||
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid url");
|
||||
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid url");
|
||||
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid url");
|
||||
@@ -157,7 +141,7 @@ impl Object for DbActor {
|
||||
|
||||
Ok(Some(DbActor {
|
||||
user_id: user.id().clone(),
|
||||
email: user.email().value().to_string(),
|
||||
username: user.username().value().to_string(),
|
||||
public_key_pem: public_key,
|
||||
private_key_pem: private_key,
|
||||
inbox_url,
|
||||
@@ -179,18 +163,13 @@ impl Object for DbActor {
|
||||
Ok(Person {
|
||||
kind: Default::default(),
|
||||
id: self.ap_id.clone().into(),
|
||||
preferred_username: self
|
||||
.email
|
||||
.split('@')
|
||||
.next()
|
||||
.unwrap_or(&self.email)
|
||||
.to_string(),
|
||||
preferred_username: self.username.clone(),
|
||||
inbox: self.inbox_url.clone(),
|
||||
outbox: self.outbox_url.clone(),
|
||||
followers: self.followers_url.clone(),
|
||||
following: self.following_url.clone(),
|
||||
public_key,
|
||||
name: Some(self.email.clone()),
|
||||
name: Some(self.username.clone()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -228,9 +207,7 @@ impl Object for DbActor {
|
||||
|
||||
Ok(DbActor {
|
||||
user_id,
|
||||
email: json
|
||||
.name
|
||||
.unwrap_or_else(|| json.preferred_username.clone()),
|
||||
username: json.preferred_username.clone(),
|
||||
public_key_pem: json.public_key.public_key_pem,
|
||||
private_key_pem: None,
|
||||
inbox_url,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use domain::ports::UserRepository;
|
||||
use domain::ports::{MovieRepository, UserRepository};
|
||||
|
||||
use crate::repository::FederationRepository;
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::repository::FederationRepository;
|
||||
pub struct FederationData {
|
||||
pub(crate) federation_repo: Arc<dyn FederationRepository>,
|
||||
pub(crate) user_repo: Arc<dyn UserRepository>,
|
||||
pub(crate) movie_repo: Arc<dyn MovieRepository>,
|
||||
pub(crate) base_url: String,
|
||||
pub(crate) domain: String,
|
||||
}
|
||||
@@ -16,6 +17,7 @@ impl FederationData {
|
||||
pub fn new(
|
||||
federation_repo: Arc<dyn FederationRepository>,
|
||||
user_repo: Arc<dyn UserRepository>,
|
||||
movie_repo: Arc<dyn MovieRepository>,
|
||||
base_url: String,
|
||||
) -> Self {
|
||||
let domain = base_url
|
||||
@@ -28,6 +30,7 @@ impl FederationData {
|
||||
Self {
|
||||
federation_repo,
|
||||
user_repo,
|
||||
movie_repo,
|
||||
base_url,
|
||||
domain,
|
||||
}
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
use axum::http::StatusCode;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Error(pub(crate) anyhow::Error);
|
||||
pub struct Error(pub(crate) anyhow::Error, pub(crate) StatusCode);
|
||||
|
||||
impl Error {
|
||||
pub fn not_found(e: impl Into<anyhow::Error>) -> Self {
|
||||
Self(e.into(), StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
pub fn bad_request(e: impl Into<anyhow::Error>) -> Self {
|
||||
Self(e.into(), StatusCode::BAD_REQUEST)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
@@ -14,23 +27,23 @@ where
|
||||
T: Into<anyhow::Error>,
|
||||
{
|
||||
fn from(t: T) -> Self {
|
||||
Error(t.into())
|
||||
Error(t.into(), StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
}
|
||||
|
||||
impl axum::response::IntoResponse for Error {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
let msg = self.0.to_string();
|
||||
let status = if msg.contains("not found") {
|
||||
tracing::debug!(error = %msg, "AP: not found");
|
||||
(axum::http::StatusCode::NOT_FOUND, "Not found")
|
||||
} else if msg.contains("invalid") || msg.contains("bad") {
|
||||
tracing::debug!(error = %msg, "AP: bad request");
|
||||
(axum::http::StatusCode::BAD_REQUEST, "Bad request")
|
||||
let status = self.1;
|
||||
if status.is_server_error() {
|
||||
tracing::error!(error = %self.0, status = status.as_u16(), "federation error");
|
||||
} else {
|
||||
tracing::error!(error = %msg, "AP: internal error");
|
||||
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
|
||||
tracing::debug!(error = %self.0, status = status.as_u16(), "federation response");
|
||||
}
|
||||
let body = if status.is_server_error() {
|
||||
"internal server error".to_string()
|
||||
} else {
|
||||
self.0.to_string()
|
||||
};
|
||||
status.into_response()
|
||||
(status, body).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@ use activitypub_federation::{
|
||||
activity_sending::SendActivityTask,
|
||||
fetch::object_id::ObjectId,
|
||||
protocol::context::WithContext,
|
||||
traits::Object,
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use chrono::{DateTime, Utc};
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
events::DomainEvent,
|
||||
@@ -15,9 +15,9 @@ use url::Url;
|
||||
|
||||
use crate::{
|
||||
activities::CreateActivity,
|
||||
actors::{actor_url, get_local_actor},
|
||||
actors::get_local_actor,
|
||||
federation::ApFederationConfig,
|
||||
objects::{review_url, ReviewObject},
|
||||
objects::DbReview,
|
||||
repository::FollowerStatus,
|
||||
};
|
||||
|
||||
@@ -42,11 +42,9 @@ impl EventHandler for ActivityPubEventHandler {
|
||||
DomainEvent::ReviewLogged {
|
||||
review_id,
|
||||
user_id,
|
||||
rating,
|
||||
watched_at,
|
||||
..
|
||||
} => self
|
||||
.on_review_logged(user_id, review_id, rating.value(), *watched_at)
|
||||
.on_review_logged(user_id, review_id)
|
||||
.await
|
||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
||||
_ => Ok(()),
|
||||
@@ -59,47 +57,42 @@ impl ActivityPubEventHandler {
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
review_id: &ReviewId,
|
||||
rating: u8,
|
||||
watched_at: chrono::NaiveDateTime,
|
||||
) -> anyhow::Result<()> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
|
||||
let followers = data.federation_repo.get_followers(user_id.clone()).await?;
|
||||
tracing::debug!(user_id = %user_id.value(), count = followers.len(), "AP: got followers for review");
|
||||
|
||||
let accepted: Vec<_> = followers
|
||||
.into_iter()
|
||||
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||
.collect();
|
||||
|
||||
tracing::debug!(accepted = accepted.len(), "AP: accepted followers");
|
||||
|
||||
if accepted.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let review = match data.movie_repo.get_review_by_id(review_id).await? {
|
||||
Some(r) => r,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
let local_actor = get_local_actor(user_id.clone(), &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let review_id_url = review_url(&self.base_url, review_id);
|
||||
let actor_id = actor_url(&self.base_url, user_id);
|
||||
let activity_id = Url::parse(&format!(
|
||||
"{}/activities/{}",
|
||||
self.base_url,
|
||||
uuid::Uuid::new_v4()
|
||||
))?;
|
||||
let activity_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let stars = "\u{2B50}".repeat(rating as usize);
|
||||
let now = DateTime::from_naive_utc_and_offset(watched_at, Utc);
|
||||
|
||||
let object = ReviewObject {
|
||||
kind: "Review".to_string(),
|
||||
id: review_id_url.into(),
|
||||
attributed_to: actor_id.into(),
|
||||
content: format!("{} (movie review)", stars),
|
||||
published: Utc::now(),
|
||||
movie_title: "Unknown".to_string(), // TODO: fetch from MovieRepository
|
||||
rating,
|
||||
comment: None,
|
||||
watched_at: now,
|
||||
let db_review = DbReview {
|
||||
ap_id: crate::urls::review_url(&self.base_url, review_id),
|
||||
review,
|
||||
};
|
||||
let object = db_review
|
||||
.into_json(&data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let create = CreateActivity {
|
||||
id: activity_id,
|
||||
@@ -111,15 +104,23 @@ impl ActivityPubEventHandler {
|
||||
|
||||
let inboxes: Vec<Url> = accepted
|
||||
.iter()
|
||||
.filter_map(|f| Url::parse(&f.actor.inbox_url).ok())
|
||||
.filter_map(|f| {
|
||||
let url = Url::parse(&f.actor.inbox_url);
|
||||
if url.is_err() {
|
||||
tracing::warn!(inbox = %f.actor.inbox_url, "AP: invalid inbox URL, skipping follower");
|
||||
}
|
||||
url.ok()
|
||||
})
|
||||
.collect();
|
||||
|
||||
tracing::debug!(inboxes = inboxes.len(), "AP: delivering to inboxes");
|
||||
|
||||
let sends =
|
||||
SendActivityTask::prepare(&create_with_ctx, &local_actor, inboxes, &data).await?;
|
||||
for send in sends {
|
||||
if let Err(e) = send.sign_and_send(&data).await {
|
||||
tracing::warn!(error = %e, "failed to deliver activity to follower");
|
||||
}
|
||||
tracing::debug!(sends = sends.len(), "AP: prepared sends");
|
||||
let failures = crate::service::send_with_retry(sends, &data).await;
|
||||
if !failures.is_empty() {
|
||||
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,18 +1,42 @@
|
||||
use activitypub_federation::config::{Data, FederationConfig, FederationMiddleware};
|
||||
use activitypub_federation::config::{Data, FederationConfig, FederationMiddleware, UrlVerifier};
|
||||
use activitypub_federation::error::Error as FedError;
|
||||
use url::Url;
|
||||
|
||||
use crate::data::FederationData;
|
||||
|
||||
// In debug mode, allow all URLs (including http://localhost:3000 where the
|
||||
// port colon would otherwise fail the default domain character check).
|
||||
#[derive(Clone)]
|
||||
struct PermissiveVerifier;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl UrlVerifier for PermissiveVerifier {
|
||||
async fn verify(&self, _url: &Url) -> Result<(), FedError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ApFederationConfig(pub FederationConfig<FederationData>);
|
||||
|
||||
impl ApFederationConfig {
|
||||
pub async fn new(data: FederationData, debug: bool) -> anyhow::Result<Self> {
|
||||
let config = FederationConfig::builder()
|
||||
.domain(&data.domain)
|
||||
.app_data(data)
|
||||
.debug(debug)
|
||||
.build()
|
||||
.await?;
|
||||
let config = if debug {
|
||||
FederationConfig::builder()
|
||||
.domain(&data.domain)
|
||||
.app_data(data)
|
||||
.debug(true)
|
||||
.url_verifier(Box::new(PermissiveVerifier))
|
||||
.build()
|
||||
.await?
|
||||
} else {
|
||||
FederationConfig::builder()
|
||||
.domain(&data.domain)
|
||||
.app_data(data)
|
||||
.debug(false)
|
||||
.build()
|
||||
.await?
|
||||
};
|
||||
Ok(Self(config))
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,17 @@ use domain::value_objects::UserId;
|
||||
|
||||
use crate::data::FederationData;
|
||||
use crate::error::Error;
|
||||
use crate::repository::FollowerStatus;
|
||||
|
||||
fn ordered_collection(id: String, total: usize, items: Vec<String>) -> serde_json::Value {
|
||||
json!({
|
||||
"@context": "https://www.w3.org/ns/activitystreams",
|
||||
"type": "OrderedCollection",
|
||||
"id": id,
|
||||
"totalItems": total,
|
||||
"orderedItems": items,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn followers_handler(
|
||||
Path(user_id_str): Path<String>,
|
||||
@@ -13,25 +24,29 @@ pub async fn followers_handler(
|
||||
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||
let user_id = UserId::from_uuid(
|
||||
uuid::Uuid::parse_str(&user_id_str)
|
||||
.map_err(|_| Error(anyhow::anyhow!("invalid user id")))?,
|
||||
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?,
|
||||
);
|
||||
|
||||
// verify user exists
|
||||
data.user_repo
|
||||
.find_by_id(&user_id)
|
||||
.await
|
||||
.map_err(|e| Error(e.into()))?
|
||||
.ok_or_else(|| Error(anyhow::anyhow!("user not found")))?;
|
||||
.map_err(Error::from)?
|
||||
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||
|
||||
let followers = data
|
||||
.federation_repo
|
||||
.get_followers(user_id)
|
||||
.await
|
||||
.map_err(Error::from)?;
|
||||
|
||||
let items: Vec<String> = followers
|
||||
.into_iter()
|
||||
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||
.map(|f| f.actor.url)
|
||||
.collect();
|
||||
|
||||
let id = format!("{}/users/{}/followers", data.base_url, user_id_str);
|
||||
// TODO(ap): implement pagination
|
||||
Ok(FederationJson(json!({
|
||||
"@context": "https://www.w3.org/ns/activitystreams",
|
||||
"type": "OrderedCollection",
|
||||
"id": id,
|
||||
"totalItems": 0,
|
||||
"orderedItems": []
|
||||
})))
|
||||
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||
}
|
||||
|
||||
pub async fn following_handler(
|
||||
@@ -40,23 +55,26 @@ pub async fn following_handler(
|
||||
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||
let user_id = UserId::from_uuid(
|
||||
uuid::Uuid::parse_str(&user_id_str)
|
||||
.map_err(|_| Error(anyhow::anyhow!("invalid user id")))?,
|
||||
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?,
|
||||
);
|
||||
|
||||
// verify user exists
|
||||
data.user_repo
|
||||
.find_by_id(&user_id)
|
||||
.await
|
||||
.map_err(|e| Error(e.into()))?
|
||||
.ok_or_else(|| Error(anyhow::anyhow!("user not found")))?;
|
||||
.map_err(Error::from)?
|
||||
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||
|
||||
let following = data
|
||||
.federation_repo
|
||||
.get_following(user_id)
|
||||
.await
|
||||
.map_err(Error::from)?;
|
||||
|
||||
let items: Vec<String> = following
|
||||
.into_iter()
|
||||
.map(|a| a.url)
|
||||
.collect();
|
||||
|
||||
let id = format!("{}/users/{}/following", data.base_url, user_id_str);
|
||||
// TODO(ap): implement pagination
|
||||
Ok(FederationJson(json!({
|
||||
"@context": "https://www.w3.org/ns/activitystreams",
|
||||
"type": "OrderedCollection",
|
||||
"id": id,
|
||||
"totalItems": 0,
|
||||
"orderedItems": []
|
||||
})))
|
||||
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod objects;
|
||||
pub mod outbox;
|
||||
pub mod repository;
|
||||
pub mod service;
|
||||
pub(crate) mod urls;
|
||||
pub mod webfinger;
|
||||
|
||||
pub use data::FederationData;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use activitypub_federation::{
|
||||
config::Data,
|
||||
fetch::object_id::ObjectId,
|
||||
kinds::object::NoteType,
|
||||
protocol::verification::verify_domains_match,
|
||||
traits::Object,
|
||||
};
|
||||
@@ -19,12 +20,16 @@ use crate::error::Error;
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReviewObject {
|
||||
#[serde(rename = "type")]
|
||||
pub(crate) kind: String,
|
||||
pub(crate) kind: NoteType,
|
||||
pub(crate) id: ObjectId<DbReview>,
|
||||
pub(crate) attributed_to: ObjectId<DbActor>,
|
||||
pub(crate) content: String,
|
||||
pub(crate) published: DateTime<Utc>,
|
||||
pub(crate) movie_title: String,
|
||||
#[serde(default)]
|
||||
pub(crate) release_year: u16, // 0 = unknown; default for old AP messages
|
||||
#[serde(default)]
|
||||
pub(crate) poster_url: Option<String>,
|
||||
pub(crate) rating: u8,
|
||||
pub(crate) comment: Option<String>,
|
||||
pub(crate) watched_at: DateTime<Utc>,
|
||||
@@ -36,10 +41,6 @@ pub struct DbReview {
|
||||
pub ap_id: Url,
|
||||
}
|
||||
|
||||
pub fn review_url(base_url: &str, review_id: &ReviewId) -> Url {
|
||||
Url::parse(&format!("{}/reviews/{}", base_url, review_id.value())).expect("valid review url")
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Object for DbReview {
|
||||
type DataType = FederationData;
|
||||
@@ -60,26 +61,39 @@ impl Object for DbReview {
|
||||
|
||||
async fn into_json(self, data: &Data<Self::DataType>) -> Result<Self::Kind, Self::Error> {
|
||||
let r = &self.review;
|
||||
let ap_id = review_url(&data.base_url, r.id());
|
||||
let actor_url = crate::actors::actor_url(&data.base_url, r.user_id());
|
||||
let ap_id = crate::urls::review_url(&data.base_url, r.id());
|
||||
let actor_url = crate::urls::actor_url(&data.base_url, r.user_id());
|
||||
|
||||
let movie = data.movie_repo.get_movie_by_id(r.movie_id()).await
|
||||
.ok().flatten();
|
||||
let movie_title = movie.as_ref()
|
||||
.map(|m| m.title().value().to_string())
|
||||
.unwrap_or_else(|| "Unknown".to_string());
|
||||
let release_year = movie.as_ref()
|
||||
.map(|m| m.release_year().value())
|
||||
.unwrap_or(0);
|
||||
let poster_url = movie.as_ref()
|
||||
.and_then(|m| m.poster_path())
|
||||
.map(|p| format!("{}/posters/{}", data.base_url, p.value()));
|
||||
|
||||
let stars: String = "\u{2B50}".repeat(r.rating().value() as usize);
|
||||
let comment_text = r.comment().map(|c| c.value().to_string());
|
||||
// TODO(ap): fetch movie title from MovieRepository via FederationData
|
||||
let movie_title = "Unknown".to_string();
|
||||
|
||||
let fallback = match &comment_text {
|
||||
Some(c) => format!("{} Watched '{}': {}", stars, movie_title, c),
|
||||
None => format!("{} Watched '{}'", stars, movie_title),
|
||||
let year_str = if release_year > 0 { format!(" ({})", release_year) } else { String::new() };
|
||||
let watched_str = format!("Watched: {}", r.watched_at().format("%b %-d, %Y"));
|
||||
let content = match &comment_text {
|
||||
Some(c) => format!("{} {}{}\n{}\n{}", stars, movie_title, year_str, c, watched_str),
|
||||
None => format!("{} {}{}\n{}", stars, movie_title, year_str, watched_str),
|
||||
};
|
||||
|
||||
Ok(ReviewObject {
|
||||
kind: "Review".to_string(),
|
||||
kind: NoteType::default(),
|
||||
id: ap_id.into(),
|
||||
attributed_to: actor_url.into(),
|
||||
content: fallback,
|
||||
content,
|
||||
published: DateTime::from_naive_utc_and_offset(*r.created_at(), Utc),
|
||||
movie_title,
|
||||
release_year,
|
||||
poster_url,
|
||||
rating: r.rating().value(),
|
||||
comment: comment_text,
|
||||
watched_at: DateTime::from_naive_utc_and_offset(*r.watched_at(), Utc),
|
||||
@@ -102,19 +116,17 @@ impl Object for DbReview {
|
||||
let actor_url = json.attributed_to.inner().to_string();
|
||||
|
||||
let review_id = ReviewId::generate();
|
||||
// TODO(ap): create stub movie/user entries in DB so feed JOIN queries work.
|
||||
// For now, use deterministic UUIDs from content hash; reviews will be orphaned in JOINs.
|
||||
let movie_id_uuid = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, json.movie_title.as_bytes());
|
||||
let movie_id = domain::value_objects::MovieId::from_uuid(movie_id_uuid);
|
||||
let user_id_uuid = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, actor_url.as_bytes());
|
||||
let user_id = domain::value_objects::UserId::from_uuid(user_id_uuid);
|
||||
let rating = domain::value_objects::Rating::new(json.rating.min(5))
|
||||
.map_err(|e| Error(anyhow::anyhow!("{}", e)))?;
|
||||
.map_err(|e| Error::bad_request(anyhow::anyhow!("{}", e)))?;
|
||||
let comment = json
|
||||
.comment
|
||||
.map(|c| domain::value_objects::Comment::new(c))
|
||||
.transpose()
|
||||
.map_err(|e| Error(anyhow::anyhow!("{}", e)))?;
|
||||
.map_err(|e| Error::bad_request(anyhow::anyhow!("{}", e)))?;
|
||||
let watched_at = json.watched_at.naive_utc();
|
||||
let created_at = json.published.naive_utc();
|
||||
|
||||
@@ -129,9 +141,9 @@ impl Object for DbReview {
|
||||
ReviewSource::Remote { actor_url },
|
||||
);
|
||||
|
||||
let ap_id = review_url(&data.base_url, review.id());
|
||||
data.federation_repo.save_remote_review(&review).await?;
|
||||
let ap_id_url = json.id.into_inner();
|
||||
data.federation_repo.save_remote_review(&review, ap_id_url.as_str(), &json.movie_title, json.release_year, json.poster_url.as_deref()).await?;
|
||||
|
||||
Ok(DbReview { review, ap_id })
|
||||
Ok(DbReview { review, ap_id: ap_id_url })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use activitypub_federation::{axum::json::FederationJson, config::Data};
|
||||
use axum::extract::Path;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use domain::value_objects::UserId;
|
||||
use domain::{models::ReviewSource, value_objects::UserId};
|
||||
|
||||
use crate::data::FederationData;
|
||||
use crate::error::Error;
|
||||
@@ -24,15 +24,25 @@ pub async fn outbox_handler(
|
||||
data: Data<FederationData>,
|
||||
) -> Result<FederationJson<OrderedCollection>, Error> {
|
||||
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||
.map_err(|_| Error(anyhow::anyhow!("invalid user id")))?;
|
||||
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||
let user_id = UserId::from_uuid(uuid);
|
||||
|
||||
// verify user exists
|
||||
data.user_repo
|
||||
.find_by_id(&user_id)
|
||||
.await
|
||||
.map_err(|e| Error(e.into()))?
|
||||
.ok_or_else(|| Error(anyhow::anyhow!("user not found")))?;
|
||||
.map_err(Error::from)?
|
||||
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||
|
||||
let history = data
|
||||
.movie_repo
|
||||
.get_user_history(&user_id)
|
||||
.await
|
||||
.map_err(Error::from)?;
|
||||
|
||||
let local_count = history
|
||||
.iter()
|
||||
.filter(|e| matches!(e.review().source(), ReviewSource::Local))
|
||||
.count();
|
||||
|
||||
let outbox_url = format!("{}/users/{}/outbox", data.base_url, user_id_str);
|
||||
|
||||
@@ -40,7 +50,7 @@ pub async fn outbox_handler(
|
||||
context: "https://www.w3.org/ns/activitystreams".to_string(),
|
||||
kind: "OrderedCollection".to_string(),
|
||||
id: outbox_url,
|
||||
total_items: 0,
|
||||
total_items: local_count as u64,
|
||||
ordered_items: vec![],
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use chrono::NaiveDateTime;
|
||||
use domain::models::Review;
|
||||
use domain::value_objects::UserId;
|
||||
|
||||
@@ -10,6 +11,12 @@ pub enum FollowerStatus {
|
||||
Rejected,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum FollowingStatus {
|
||||
Pending,
|
||||
Accepted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemoteActor {
|
||||
pub url: String,
|
||||
@@ -31,13 +38,38 @@ pub trait FederationRepository: Send + Sync {
|
||||
async fn remove_follower(&self, local_user_id: UserId, remote_actor_url: &str) -> Result<()>;
|
||||
async fn get_followers(&self, local_user_id: UserId) -> Result<Vec<Follower>>;
|
||||
async fn update_follower_status(&self, local_user_id: UserId, remote_actor_url: &str, status: FollowerStatus) -> Result<()>;
|
||||
async fn add_following(&self, local_user_id: UserId, actor: RemoteActor) -> Result<()>;
|
||||
async fn add_following(&self, local_user_id: UserId, actor: RemoteActor, follow_activity_id: &str) -> Result<()>;
|
||||
async fn get_follow_activity_id(&self, local_user_id: UserId, remote_actor_url: &str) -> Result<Option<String>>;
|
||||
async fn remove_following(&self, local_user_id: UserId, actor_url: &str) -> Result<()>;
|
||||
async fn get_following(&self, local_user_id: UserId) -> Result<Vec<RemoteActor>>;
|
||||
async fn count_following(&self, local_user_id: UserId) -> Result<usize>;
|
||||
async fn upsert_remote_actor(&self, actor: RemoteActor) -> Result<()>;
|
||||
async fn get_remote_actor(&self, actor_url: &str) -> Result<Option<RemoteActor>>;
|
||||
async fn save_remote_review(&self, review: &Review) -> Result<()>;
|
||||
async fn save_remote_review(
|
||||
&self,
|
||||
review: &Review,
|
||||
ap_id: &str,
|
||||
movie_title: &str,
|
||||
release_year: u16,
|
||||
poster_url: Option<&str>,
|
||||
) -> Result<()>;
|
||||
async fn delete_remote_review_by_ap_id(&self, ap_id: &str, actor_url: &str) -> Result<()>;
|
||||
async fn update_remote_review(
|
||||
&self,
|
||||
ap_id: &str,
|
||||
actor_url: &str,
|
||||
rating: u8,
|
||||
comment: Option<&str>,
|
||||
watched_at: NaiveDateTime,
|
||||
) -> Result<()>;
|
||||
async fn get_local_actor_keypair(&self, user_id: UserId) -> Result<Option<(String, String)>>;
|
||||
async fn save_local_actor_keypair(&self, user_id: UserId, public_key: String, private_key: String) -> Result<()>;
|
||||
async fn delete_remote_reviews_by_actor(&self, actor_url: &str) -> Result<()>;
|
||||
async fn get_pending_followers(&self, local_user_id: UserId) -> Result<Vec<RemoteActor>>;
|
||||
async fn update_following_status(
|
||||
&self,
|
||||
local_user_id: UserId,
|
||||
remote_actor_url: &str,
|
||||
status: FollowingStatus,
|
||||
) -> Result<()>;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use domain::{ports::UserRepository, value_objects::UserId};
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
activities::{FollowActivity, UndoActivity},
|
||||
activities::{AcceptActivity, CreateActivity, FollowActivity, RejectActivity, UndoActivity},
|
||||
actor_handler::actor_handler,
|
||||
actors::{get_local_actor, DbActor},
|
||||
data::FederationData,
|
||||
@@ -21,10 +21,37 @@ use crate::{
|
||||
followers_handler::{followers_handler, following_handler},
|
||||
inbox::inbox_handler,
|
||||
outbox::outbox_handler,
|
||||
repository::{FederationRepository, RemoteActor},
|
||||
repository::{FederationRepository, FollowerStatus, RemoteActor},
|
||||
webfinger::webfinger_handler,
|
||||
};
|
||||
|
||||
pub(crate) async fn send_with_retry(
|
||||
sends: Vec<SendActivityTask>,
|
||||
data: &Data<FederationData>,
|
||||
) -> Vec<anyhow::Error> {
|
||||
let mut failures = vec![];
|
||||
for send in sends {
|
||||
let mut delay = std::time::Duration::from_secs(1);
|
||||
for attempt in 1..=3u32 {
|
||||
match send.clone().sign_and_send(data).await {
|
||||
Ok(()) => {
|
||||
break;
|
||||
}
|
||||
Err(e) if attempt < 3 => {
|
||||
tracing::warn!(attempt, error = %e, "delivery failed, retrying");
|
||||
tokio::time::sleep(delay).await;
|
||||
delay *= 2;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(attempt, error = %e, "delivery failed permanently");
|
||||
failures.push(anyhow::anyhow!(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
failures
|
||||
}
|
||||
|
||||
pub struct ActivityPubService {
|
||||
federation_config: ApFederationConfig,
|
||||
base_url: String,
|
||||
@@ -34,10 +61,11 @@ impl ActivityPubService {
|
||||
pub async fn new(
|
||||
repo: Arc<dyn FederationRepository>,
|
||||
user_repo: Arc<dyn UserRepository>,
|
||||
movie_repo: Arc<dyn domain::ports::MovieRepository>,
|
||||
base_url: String,
|
||||
debug: bool,
|
||||
) -> anyhow::Result<Self> {
|
||||
let data = FederationData::new(repo, user_repo, base_url.clone());
|
||||
let data = FederationData::new(repo, user_repo, movie_repo, base_url.clone());
|
||||
let federation_config = ApFederationConfig::new(data, debug).await?;
|
||||
Ok(Self {
|
||||
federation_config,
|
||||
@@ -53,6 +81,22 @@ impl ActivityPubService {
|
||||
self.federation_config.to_request_data()
|
||||
}
|
||||
|
||||
// Returns the AP actor document JSON for a local user.
|
||||
// Used for content negotiation in the HTML profile handler.
|
||||
pub async fn actor_json(&self, user_id_str: &str) -> anyhow::Result<String> {
|
||||
use activitypub_federation::traits::Object;
|
||||
use crate::actors::get_local_actor;
|
||||
let uuid = uuid::Uuid::parse_str(user_id_str)?;
|
||||
let user_id = UserId::from_uuid(uuid);
|
||||
let data = self.federation_config.to_request_data();
|
||||
let actor = get_local_actor(user_id, &data).await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let person = actor.into_json(&data).await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let with_context = WithContext::new_default(person);
|
||||
Ok(serde_json::to_string(&with_context)?)
|
||||
}
|
||||
|
||||
pub fn router(&self) -> Router {
|
||||
Router::new()
|
||||
.route("/.well-known/webfinger", get(webfinger_handler))
|
||||
@@ -79,11 +123,8 @@ impl ActivityPubService {
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let follow_id = Url::parse(&format!(
|
||||
"{}/activities/{}",
|
||||
self.base_url,
|
||||
uuid::Uuid::new_v4()
|
||||
))?;
|
||||
let follow_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let follow_id_str = follow_id.to_string();
|
||||
let follow = FollowActivity {
|
||||
id: follow_id,
|
||||
kind: Default::default(),
|
||||
@@ -99,24 +140,20 @@ impl ActivityPubService {
|
||||
&data,
|
||||
)
|
||||
.await?;
|
||||
for send in sends {
|
||||
send.sign_and_send(&data).await?;
|
||||
let failures = send_with_retry(sends, &data).await;
|
||||
if !failures.is_empty() {
|
||||
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||
}
|
||||
|
||||
let remote = RemoteActor {
|
||||
url: remote_actor.ap_id.to_string(),
|
||||
handle: remote_actor
|
||||
.email
|
||||
.split('@')
|
||||
.next()
|
||||
.unwrap_or(&remote_actor.email)
|
||||
.to_string(),
|
||||
handle: remote_actor.username.clone(),
|
||||
inbox_url: remote_actor.inbox_url.to_string(),
|
||||
shared_inbox_url: None,
|
||||
display_name: Some(remote_actor.email.clone()),
|
||||
display_name: Some(remote_actor.username.clone()),
|
||||
};
|
||||
data.federation_repo
|
||||
.add_following(local_user_id, remote)
|
||||
.add_following(local_user_id, remote, &follow_id_str)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
@@ -138,11 +175,14 @@ impl ActivityPubService {
|
||||
let remote_ap_id = Url::parse(actor_url_str)?;
|
||||
let inbox = Url::parse(&remote.inbox_url)?;
|
||||
|
||||
let follow_id = Url::parse(&format!(
|
||||
"{}/activities/{}",
|
||||
self.base_url,
|
||||
uuid::Uuid::new_v4()
|
||||
))?;
|
||||
let follow_activity_id_str = data
|
||||
.federation_repo
|
||||
.get_follow_activity_id(local_user_id.clone(), actor_url_str)
|
||||
.await?;
|
||||
let follow_id = match follow_activity_id_str {
|
||||
Some(id) => Url::parse(&id)?,
|
||||
None => crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||
};
|
||||
let follow = FollowActivity {
|
||||
id: follow_id,
|
||||
kind: Default::default(),
|
||||
@@ -150,11 +190,7 @@ impl ActivityPubService {
|
||||
object: ObjectId::from(remote_ap_id),
|
||||
};
|
||||
|
||||
let undo_id = Url::parse(&format!(
|
||||
"{}/activities/{}",
|
||||
self.base_url,
|
||||
uuid::Uuid::new_v4()
|
||||
))?;
|
||||
let undo_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let undo = UndoActivity {
|
||||
id: undo_id,
|
||||
kind: Default::default(),
|
||||
@@ -165,14 +201,20 @@ impl ActivityPubService {
|
||||
|
||||
let sends =
|
||||
SendActivityTask::prepare(&undo_with_ctx, &local_actor, vec![inbox], &data).await?;
|
||||
for send in sends {
|
||||
send.sign_and_send(&data).await?;
|
||||
let failures = send_with_retry(sends, &data).await;
|
||||
if !failures.is_empty() {
|
||||
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||
}
|
||||
|
||||
data.federation_repo
|
||||
.remove_following(local_user_id, actor_url_str)
|
||||
.await?;
|
||||
|
||||
data.federation_repo
|
||||
.delete_remote_reviews_by_actor(actor_url_str)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -185,4 +227,220 @@ impl ActivityPubService {
|
||||
let data = self.federation_config.to_request_data();
|
||||
data.federation_repo.count_following(local_user_id).await
|
||||
}
|
||||
|
||||
pub async fn accept_follower(
|
||||
&self,
|
||||
local_user_id: UserId,
|
||||
remote_actor_url: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
let local_actor = get_local_actor(local_user_id.clone(), &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let remote_actor = data
|
||||
.federation_repo
|
||||
.get_remote_actor(remote_actor_url)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||
|
||||
let follow_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let follow = FollowActivity {
|
||||
id: follow_id,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||
};
|
||||
let accept = AcceptActivity {
|
||||
id: crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||
object: follow,
|
||||
};
|
||||
|
||||
// Update status first so local state is correct even if delivery fails
|
||||
data.federation_repo
|
||||
.update_follower_status(local_user_id.clone(), remote_actor_url, FollowerStatus::Accepted)
|
||||
.await?;
|
||||
|
||||
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||
let sends = SendActivityTask::prepare(
|
||||
&WithContext::new_default(accept),
|
||||
&local_actor,
|
||||
vec![inbox.clone()],
|
||||
&data,
|
||||
)
|
||||
.await?;
|
||||
let failures = send_with_retry(sends, &data).await;
|
||||
if !failures.is_empty() {
|
||||
tracing::warn!("failed to deliver Accept activity, but follower is marked accepted locally");
|
||||
}
|
||||
|
||||
self.spawn_backfill(local_user_id, remote_actor.inbox_url.clone());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn reject_follower(
|
||||
&self,
|
||||
local_user_id: UserId,
|
||||
remote_actor_url: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
let local_actor = get_local_actor(local_user_id.clone(), &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let remote_actor = data
|
||||
.federation_repo
|
||||
.get_remote_actor(remote_actor_url)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||
|
||||
let follow_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let follow = FollowActivity {
|
||||
id: follow_id,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||
};
|
||||
let reject = RejectActivity {
|
||||
id: crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||
object: follow,
|
||||
};
|
||||
|
||||
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||
let sends = SendActivityTask::prepare(
|
||||
&WithContext::new_default(reject),
|
||||
&local_actor,
|
||||
vec![inbox],
|
||||
&data,
|
||||
)
|
||||
.await?;
|
||||
let failures = send_with_retry(sends, &data).await;
|
||||
if !failures.is_empty() {
|
||||
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||
}
|
||||
|
||||
data.federation_repo
|
||||
.remove_follower(local_user_id, remote_actor_url)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_pending_followers(
|
||||
&self,
|
||||
local_user_id: UserId,
|
||||
) -> anyhow::Result<Vec<RemoteActor>> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
data.federation_repo
|
||||
.get_pending_followers(local_user_id)
|
||||
.await
|
||||
}
|
||||
|
||||
fn spawn_backfill(&self, owner_user_id: UserId, follower_inbox_url: String) {
|
||||
let config = self.federation_config.clone();
|
||||
let base_url = self.base_url.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = ActivityPubService::run_backfill(
|
||||
config, base_url, owner_user_id, follower_inbox_url,
|
||||
).await {
|
||||
tracing::warn!(error = %e, "backfill: task failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn run_backfill(
|
||||
config: ApFederationConfig,
|
||||
base_url: String,
|
||||
owner_user_id: UserId,
|
||||
follower_inbox_url: String,
|
||||
) -> anyhow::Result<()> {
|
||||
const BATCH_SIZE: usize = 20;
|
||||
|
||||
let data = config.to_request_data();
|
||||
let local_actor = get_local_actor(owner_user_id.clone(), &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let inbox = Url::parse(&follower_inbox_url)?;
|
||||
|
||||
let history = data.movie_repo.get_user_history(&owner_user_id).await?;
|
||||
let local_reviews: Vec<_> = history
|
||||
.into_iter()
|
||||
.filter(|e| matches!(e.review().source(), domain::models::ReviewSource::Local))
|
||||
.collect();
|
||||
|
||||
let total = local_reviews.len();
|
||||
|
||||
let mut success_count = 0usize;
|
||||
let mut failure_count = 0usize;
|
||||
|
||||
for chunk in local_reviews.chunks(BATCH_SIZE) {
|
||||
for entry in chunk {
|
||||
match ActivityPubService::deliver_review_to_inbox(
|
||||
entry.review().clone(),
|
||||
&local_actor,
|
||||
inbox.clone(),
|
||||
&data,
|
||||
&base_url,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => success_count += 1,
|
||||
Err(_) => failure_count += 1,
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
user_id = %owner_user_id.value(),
|
||||
follower = %follower_inbox_url,
|
||||
sent = success_count,
|
||||
failed = failure_count,
|
||||
total = total,
|
||||
"backfill complete"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn deliver_review_to_inbox(
|
||||
review: domain::models::Review,
|
||||
local_actor: &DbActor,
|
||||
inbox: Url,
|
||||
data: &Data<FederationData>,
|
||||
base_url: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
use activitypub_federation::traits::Object;
|
||||
use crate::objects::DbReview;
|
||||
|
||||
let ap_id = crate::urls::review_url(base_url, review.id());
|
||||
let db_review = DbReview { review, ap_id };
|
||||
let object = db_review.into_json(data).await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let activity_id = crate::urls::activity_url(base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let create = CreateActivity {
|
||||
id: activity_id,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||
object,
|
||||
};
|
||||
|
||||
let sends = SendActivityTask::prepare(
|
||||
&WithContext::new_default(create),
|
||||
local_actor,
|
||||
vec![inbox],
|
||||
data,
|
||||
).await?;
|
||||
let failures = send_with_retry(sends, data).await;
|
||||
if let Some(e) = failures.into_iter().next() {
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
31
crates/adapters/activitypub/src/urls.rs
Normal file
31
crates/adapters/activitypub/src/urls.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
use domain::value_objects::{UserId, ReviewId};
|
||||
use crate::error::Error;
|
||||
|
||||
/// Extracts a UserId from a URL like `https://example.com/users/{uuid}[/...]`
|
||||
pub fn extract_user_id_from_url(url: &Url) -> Option<UserId> {
|
||||
let path = url.path();
|
||||
path.strip_prefix("/users/")
|
||||
.and_then(|s| s.split('/').next())
|
||||
.and_then(|uid_str| Uuid::parse_str(uid_str).ok())
|
||||
.map(UserId::from_uuid)
|
||||
}
|
||||
|
||||
/// Generates a fresh activity URL: `{base_url}/activities/{uuid}`
|
||||
pub fn activity_url(base_url: &str) -> Result<Url, Error> {
|
||||
Url::parse(&format!("{}/activities/{}", base_url, Uuid::new_v4()))
|
||||
.map_err(|e| Error::bad_request(anyhow::anyhow!(e)))
|
||||
}
|
||||
|
||||
/// Builds the canonical actor URL: `{base_url}/users/{user_id}`
|
||||
pub fn actor_url(base_url: &str, user_id: &UserId) -> Url {
|
||||
Url::parse(&format!("{}/users/{}", base_url, user_id.value()))
|
||||
.expect("base_url is always a valid URL prefix")
|
||||
}
|
||||
|
||||
/// Builds the canonical review URL: `{base_url}/reviews/{review_id}`
|
||||
pub fn review_url(base_url: &str, review_id: &ReviewId) -> Url {
|
||||
Url::parse(&format!("{}/reviews/{}", base_url, review_id.value()))
|
||||
.expect("base_url is always a valid URL prefix")
|
||||
}
|
||||
@@ -9,7 +9,8 @@ use axum::{
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::actors::actor_url;
|
||||
use domain::value_objects::Username;
|
||||
|
||||
use crate::data::FederationData;
|
||||
use crate::error::Error;
|
||||
|
||||
@@ -24,19 +25,16 @@ pub async fn webfinger_handler(
|
||||
) -> Result<Response, Error> {
|
||||
let name = extract_webfinger_name(&query.resource, &data)?;
|
||||
|
||||
// Look up user by email username@domain
|
||||
let email_str = format!("{}@{}", name, data.domain);
|
||||
let email = domain::value_objects::Email::new(email_str)
|
||||
.map_err(|e| Error(anyhow::anyhow!("{}", e)))?;
|
||||
|
||||
let username = Username::new(name.to_string())
|
||||
.map_err(|e| Error::bad_request(anyhow::anyhow!(e.to_string())))?;
|
||||
let user = data
|
||||
.user_repo
|
||||
.find_by_email(&email)
|
||||
.find_by_username(&username)
|
||||
.await
|
||||
.map_err(|e| Error(e.into()))?
|
||||
.ok_or_else(|| Error(anyhow::anyhow!("user not found")))?;
|
||||
.map_err(Error::from)?
|
||||
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||
|
||||
let ap_id = actor_url(&data.base_url, user.id());
|
||||
let ap_id = crate::urls::actor_url(&data.base_url, user.id());
|
||||
|
||||
let wf: Webfinger = build_webfinger_response(query.resource, ap_id);
|
||||
let body = serde_json::to_string(&wf)
|
||||
|
||||
Reference in New Issue
Block a user