activitypub-federation-rust/examples/local_federation/objects/person.rs

194 lines
5.3 KiB
Rust
Raw Normal View History

2022-06-02 16:47:12 +05:30
use crate::{
activities::{accept::Accept, create_post::CreateNote, follow::Follow},
2022-06-02 16:47:12 +05:30
error::Error,
instance::DatabaseHandle,
objects::post::DbPost,
2022-11-26 21:42:08 +05:30
utils::generate_object_id,
2022-06-02 16:47:12 +05:30
};
use activitypub_federation::{
core::{
2022-06-03 17:30:16 +05:30
activity_queue::send_activity,
2022-06-02 16:47:12 +05:30
object_id::ObjectId,
signatures::{generate_actor_keypair, PublicKey},
2022-06-02 16:47:12 +05:30
},
kinds::actor::PersonType,
protocol::context::WithContext,
request_data::RequestData,
2022-06-03 17:30:16 +05:30
traits::{ActivityHandler, Actor, ApubObject},
2022-06-02 16:47:12 +05:30
};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
2022-06-02 16:47:12 +05:30
use url::Url;
#[derive(Debug, Clone)]
pub struct DbUser {
pub name: String,
pub ap_id: ObjectId<DbUser>,
2022-06-02 16:47:12 +05:30
pub inbox: Url,
// exists for all users (necessary to verify http signatures)
public_key: String,
// exists only for local users
private_key: Option<String>,
pub followers: Vec<Url>,
pub local: bool,
}
/// List of all activities which this actor can receive.
#[derive(Deserialize, Serialize, Debug)]
#[serde(untagged)]
2022-11-14 17:34:36 +05:30
#[enum_delegate::implement(ActivityHandler)]
2022-06-02 16:47:12 +05:30
pub enum PersonAcceptedActivities {
Follow(Follow),
Accept(Accept),
CreateNote(CreateNote),
}
impl DbUser {
pub fn new(hostname: &str, name: String) -> Result<DbUser, Error> {
let ap_id = Url::parse(&format!("http://{}/{}", hostname, &name))?.into();
let inbox = Url::parse(&format!("http://{}/{}/inbox", hostname, &name))?;
let keypair = generate_actor_keypair()?;
Ok(DbUser {
name,
2022-06-02 16:47:12 +05:30
ap_id,
inbox,
public_key: keypair.public_key,
private_key: Some(keypair.private_key),
followers: vec![],
local: true,
})
2022-06-02 16:47:12 +05:30
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Person {
#[serde(rename = "type")]
kind: PersonType,
preferred_username: String,
id: ObjectId<DbUser>,
2022-06-02 16:47:12 +05:30
inbox: Url,
public_key: PublicKey,
}
impl DbUser {
2022-06-02 16:47:12 +05:30
pub fn followers(&self) -> &Vec<Url> {
&self.followers
}
pub fn followers_url(&self) -> Result<Url, Error> {
Ok(Url::parse(&format!("{}/followers", self.ap_id.inner()))?)
}
fn public_key(&self) -> PublicKey {
PublicKey::new_main_key(self.ap_id.clone().into_inner(), self.public_key.clone())
}
pub async fn follow(
&self,
other: &DbUser,
data: &RequestData<DatabaseHandle>,
) -> Result<(), Error> {
let id = generate_object_id(data.hostname())?;
2022-06-02 16:47:12 +05:30
let follow = Follow::new(self.ap_id.clone(), other.ap_id.clone(), id.clone());
self.send(follow, vec![other.shared_inbox_or_inbox()], data)
.await?;
2022-06-02 16:47:12 +05:30
Ok(())
}
pub async fn post(
&self,
post: DbPost,
data: &RequestData<DatabaseHandle>,
) -> Result<(), Error> {
let id = generate_object_id(data.hostname())?;
let create = CreateNote::new(post.into_apub(data).await?, id.clone());
2022-06-06 20:06:44 +05:30
let mut inboxes = vec![];
2022-06-02 16:47:12 +05:30
for f in self.followers.clone() {
let user: DbUser = ObjectId::new(f).dereference(data).await?;
2022-06-06 20:06:44 +05:30
inboxes.push(user.shared_inbox_or_inbox());
2022-06-02 16:47:12 +05:30
}
self.send(create, inboxes, data).await?;
2022-06-02 16:47:12 +05:30
Ok(())
}
2022-06-06 20:06:44 +05:30
pub(crate) async fn send<Activity>(
2022-06-02 16:47:12 +05:30
&self,
activity: Activity,
2022-06-06 20:06:44 +05:30
recipients: Vec<Url>,
data: &RequestData<DatabaseHandle>,
2022-06-03 17:30:16 +05:30
) -> Result<(), <Activity as ActivityHandler>::Error>
where
Activity: ActivityHandler + Serialize + Debug + Send + Sync,
2022-06-03 17:30:16 +05:30
<Activity as ActivityHandler>::Error: From<anyhow::Error> + From<serde_json::Error>,
{
let activity = WithContext::new_default(activity);
send_activity(
activity,
self.public_key(),
self.private_key.clone().unwrap(),
2022-06-03 17:30:16 +05:30
recipients,
data,
2022-06-03 17:30:16 +05:30
)
2022-06-02 16:47:12 +05:30
.await?;
Ok(())
}
}
#[async_trait::async_trait]
impl ApubObject for DbUser {
type DataType = DatabaseHandle;
2022-06-02 16:47:12 +05:30
type ApubType = Person;
type Error = Error;
2022-06-02 16:47:12 +05:30
async fn read_from_apub_id(
object_id: Url,
data: &RequestData<Self::DataType>,
2022-06-02 16:47:12 +05:30
) -> Result<Option<Self>, Self::Error> {
let users = data.users.lock().unwrap();
let res = users
.clone()
.into_iter()
.find(|u| u.ap_id.inner() == &object_id);
Ok(res)
}
async fn into_apub(
self,
_data: &RequestData<Self::DataType>,
) -> Result<Self::ApubType, Self::Error> {
2022-06-02 16:47:12 +05:30
Ok(Person {
preferred_username: self.name.clone(),
2022-06-02 16:47:12 +05:30
kind: Default::default(),
id: self.ap_id.clone(),
inbox: self.inbox.clone(),
public_key: self.public_key(),
})
}
async fn from_apub(
apub: Self::ApubType,
_data: &RequestData<Self::DataType>,
2022-06-02 16:47:12 +05:30
) -> Result<Self, Self::Error> {
Ok(DbUser {
name: apub.preferred_username,
2022-06-02 16:47:12 +05:30
ap_id: apub.id,
inbox: apub.inbox,
public_key: apub.public_key.public_key_pem,
private_key: None,
followers: vec![],
local: false,
})
}
}
impl Actor for DbUser {
2022-06-02 16:47:12 +05:30
fn public_key(&self) -> &str {
&self.public_key
}
2022-06-03 17:30:16 +05:30
fn inbox(&self) -> Url {
self.inbox.clone()
}
2022-06-02 16:47:12 +05:30
}