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

203 lines
5.7 KiB
Rust
Raw Normal View History

2022-06-02 11:17:12 +00:00
use crate::{
2023-03-07 22:01:36 +00:00
activities::{accept::Accept, create_post::CreatePost, follow::Follow},
2022-06-02 11:17:12 +00:00
error::Error,
instance::DatabaseHandle,
objects::post::DbPost,
2022-11-26 16:12:08 +00:00
utils::generate_object_id,
2022-06-02 11:17:12 +00:00
};
use activitypub_federation::{
2023-03-06 01:17:34 +00:00
activity_queue::send_activity,
2023-03-01 23:19:10 +00:00
config::RequestData,
2023-03-06 01:17:34 +00:00
fetch::{object_id::ObjectId, webfinger::webfinger_resolve_actor},
http_signatures::generate_actor_keypair,
kinds::actor::PersonType,
2023-03-01 23:19:10 +00:00
protocol::{context::WithContext, public_key::PublicKey},
2022-06-03 12:00:16 +00:00
traits::{ActivityHandler, Actor, ApubObject},
2022-06-02 11:17:12 +00:00
};
2023-03-07 22:01:36 +00:00
use chrono::{Local, NaiveDateTime};
2022-06-02 11:17:12 +00:00
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
2022-06-02 11:17:12 +00:00
use url::Url;
#[derive(Debug, Clone)]
pub struct DbUser {
pub name: String,
pub ap_id: ObjectId<DbUser>,
2022-06-02 11:17:12 +00:00
pub inbox: Url,
// exists for all users (necessary to verify http signatures)
public_key: String,
// exists only for local users
private_key: Option<String>,
2023-03-07 22:01:36 +00:00
last_refreshed_at: NaiveDateTime,
2022-06-02 11:17:12 +00:00
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 12:04:36 +00:00
#[enum_delegate::implement(ActivityHandler)]
2022-06-02 11:17:12 +00:00
pub enum PersonAcceptedActivities {
Follow(Follow),
Accept(Accept),
2023-03-07 22:01:36 +00:00
CreateNote(CreatePost),
2022-06-02 11:17:12 +00:00
}
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 11:17:12 +00:00
ap_id,
inbox,
public_key: keypair.public_key,
private_key: Some(keypair.private_key),
2023-03-07 22:01:36 +00:00
last_refreshed_at: Local::now().naive_local(),
2022-06-02 11:17:12 +00:00
followers: vec![],
local: true,
})
2022-06-02 11:17:12 +00:00
}
}
#[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 11:17:12 +00:00
inbox: Url,
public_key: PublicKey,
}
impl DbUser {
2022-06-02 11:17:12 +00:00
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 {
2023-03-01 23:19:10 +00:00
PublicKey::new(self.ap_id.clone().into_inner(), self.public_key.clone())
2022-06-02 11:17:12 +00:00
}
pub async fn follow(
&self,
2023-03-01 23:19:10 +00:00
other: &str,
data: &RequestData<DatabaseHandle>,
) -> Result<(), Error> {
2023-03-01 23:19:10 +00:00
let other: DbUser = webfinger_resolve_actor(other, data).await?;
let id = generate_object_id(data.domain())?;
2022-06-02 11:17:12 +00:00
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 11:17:12 +00:00
Ok(())
}
pub async fn post(
&self,
post: DbPost,
data: &RequestData<DatabaseHandle>,
) -> Result<(), Error> {
2023-03-01 23:19:10 +00:00
let id = generate_object_id(data.domain())?;
2023-03-07 22:01:36 +00:00
let create = CreatePost::new(post.into_apub(data).await?, id.clone());
2022-06-06 14:36:44 +00:00
let mut inboxes = vec![];
2022-06-02 11:17:12 +00:00
for f in self.followers.clone() {
2023-03-01 23:19:10 +00:00
let user: DbUser = ObjectId::from(f).dereference(data).await?;
2022-06-06 14:36:44 +00:00
inboxes.push(user.shared_inbox_or_inbox());
2022-06-02 11:17:12 +00:00
}
self.send(create, inboxes, data).await?;
2022-06-02 11:17:12 +00:00
Ok(())
}
2022-06-06 14:36:44 +00:00
pub(crate) async fn send<Activity>(
2022-06-02 11:17:12 +00:00
&self,
activity: Activity,
2022-06-06 14:36:44 +00:00
recipients: Vec<Url>,
data: &RequestData<DatabaseHandle>,
2022-06-03 12:00:16 +00:00
) -> Result<(), <Activity as ActivityHandler>::Error>
where
Activity: ActivityHandler + Serialize + Debug + Send + Sync,
2022-06-03 12:00:16 +00:00
<Activity as ActivityHandler>::Error: From<anyhow::Error> + From<serde_json::Error>,
{
let activity = WithContext::new_default(activity);
send_activity(
activity,
self.private_key.clone().unwrap(),
2022-06-03 12:00:16 +00:00
recipients,
data,
2022-06-03 12:00:16 +00:00
)
2022-06-02 11:17:12 +00:00
.await?;
Ok(())
}
}
#[async_trait::async_trait]
impl ApubObject for DbUser {
type DataType = DatabaseHandle;
2022-06-02 11:17:12 +00:00
type ApubType = Person;
type Error = Error;
2022-06-02 11:17:12 +00:00
2023-03-07 22:01:36 +00:00
fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
Some(self.last_refreshed_at)
}
2022-06-02 11:17:12 +00:00
async fn read_from_apub_id(
object_id: Url,
data: &RequestData<Self::DataType>,
2022-06-02 11:17:12 +00:00
) -> 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 11:17:12 +00:00
Ok(Person {
preferred_username: self.name.clone(),
2022-06-02 11:17:12 +00:00
kind: Default::default(),
id: self.ap_id.clone(),
inbox: self.inbox.clone(),
public_key: self.public_key(),
})
}
async fn from_apub(
apub: Self::ApubType,
2023-03-07 22:01:36 +00:00
data: &RequestData<Self::DataType>,
2022-06-02 11:17:12 +00:00
) -> Result<Self, Self::Error> {
2023-03-07 22:01:36 +00:00
let user = DbUser {
name: apub.preferred_username,
2022-06-02 11:17:12 +00:00
ap_id: apub.id,
inbox: apub.inbox,
public_key: apub.public_key.public_key_pem,
private_key: None,
2023-03-07 22:01:36 +00:00
last_refreshed_at: Local::now().naive_local(),
2022-06-02 11:17:12 +00:00
followers: vec![],
local: false,
2023-03-07 22:01:36 +00:00
};
let mut mutex = data.users.lock().unwrap();
mutex.push(user.clone());
Ok(user)
2022-06-02 11:17:12 +00:00
}
}
impl Actor for DbUser {
2022-06-02 11:17:12 +00:00
fn public_key(&self) -> &str {
&self.public_key
}
2022-06-03 12:00:16 +00:00
fn inbox(&self) -> Url {
self.inbox.clone()
}
2022-06-02 11:17:12 +00:00
}