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

95 lines
2.6 KiB
Rust
Raw Normal View History

use crate::{error::Error, generate_object_id, instance::DatabaseHandle, objects::person::DbUser};
2022-06-02 16:47:12 +05:30
use activitypub_federation::{
config::Data,
2023-03-06 06:47:34 +05:30
fetch::object_id::ObjectId,
kinds::{object::NoteType, public},
protocol::{helpers::deserialize_one_or_many, verification::verify_domains_match},
2023-03-17 02:11:29 +05:30
traits::Object,
2022-06-02 16:47:12 +05:30
};
use serde::{Deserialize, Serialize};
use url::Url;
#[derive(Clone, Debug)]
pub struct DbPost {
2022-06-02 16:47:12 +05:30
pub text: String,
pub ap_id: ObjectId<DbPost>,
pub creator: ObjectId<DbUser>,
2022-06-02 16:47:12 +05:30
pub local: bool,
}
impl DbPost {
pub fn new(text: String, creator: ObjectId<DbUser>) -> Result<DbPost, Error> {
let ap_id = generate_object_id(creator.inner().domain().unwrap())?.into();
Ok(DbPost {
2022-06-02 16:47:12 +05:30
text,
ap_id,
2022-06-02 16:47:12 +05:30
creator,
local: true,
})
2022-06-02 16:47:12 +05:30
}
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Note {
#[serde(rename = "type")]
kind: NoteType,
id: ObjectId<DbPost>,
pub(crate) attributed_to: ObjectId<DbUser>,
2022-06-02 16:47:12 +05:30
#[serde(deserialize_with = "deserialize_one_or_many")]
pub(crate) to: Vec<Url>,
content: String,
}
#[async_trait::async_trait]
2023-03-17 02:11:29 +05:30
impl Object for DbPost {
type DataType = DatabaseHandle;
2023-03-17 02:11:29 +05:30
type Kind = Note;
type Error = Error;
2022-06-02 16:47:12 +05:30
2023-03-17 02:11:29 +05:30
async fn read_from_id(
2023-03-08 03:31:36 +05:30
object_id: Url,
data: &Data<Self::DataType>,
2022-06-02 16:47:12 +05:30
) -> Result<Option<Self>, Self::Error> {
2023-03-08 03:31:36 +05:30
let posts = data.posts.lock().unwrap();
let res = posts
.clone()
.into_iter()
.find(|u| u.ap_id.inner() == &object_id);
Ok(res)
2022-06-02 16:47:12 +05:30
}
2023-03-17 02:11:29 +05:30
async fn into_json(self, data: &Data<Self::DataType>) -> Result<Self::Kind, Self::Error> {
let creator = self.creator.dereference_local(data).await?;
2022-06-02 16:47:12 +05:30
Ok(Note {
kind: Default::default(),
id: self.ap_id,
attributed_to: self.creator,
to: vec![public(), creator.followers_url()?],
content: self.text,
})
}
async fn verify(
2023-03-17 02:11:29 +05:30
json: &Self::Kind,
expected_domain: &Url,
_data: &Data<Self::DataType>,
) -> Result<(), Self::Error> {
2023-03-17 02:11:29 +05:30
verify_domains_match(json.id.inner(), expected_domain)?;
Ok(())
}
2023-03-17 02:11:29 +05:30
async fn from_json(json: Self::Kind, data: &Data<Self::DataType>) -> Result<Self, Self::Error> {
let post = DbPost {
2023-03-17 02:11:29 +05:30
text: json.content,
ap_id: json.id,
creator: json.attributed_to,
2022-06-02 16:47:12 +05:30
local: false,
};
let mut lock = data.posts.lock().unwrap();
lock.push(post.clone());
Ok(post)
}
}