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

87 lines
2.2 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::{
2023-03-02 04:49:10 +05:30
config::RequestData,
2022-06-02 16:47:12 +05:30
core::object_id::ObjectId,
kinds::{object::NoteType, public},
protocol::helpers::deserialize_one_or_many,
2022-06-02 16:47:12 +05:30
traits::ApubObject,
};
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]
impl ApubObject for DbPost {
type DataType = DatabaseHandle;
2022-06-02 16:47:12 +05:30
type ApubType = Note;
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> {
todo!()
}
async fn into_apub(
self,
data: &RequestData<Self::DataType>,
) -> Result<Self::ApubType, 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 from_apub(
apub: Self::ApubType,
data: &RequestData<Self::DataType>,
2022-06-02 16:47:12 +05:30
) -> Result<Self, Self::Error> {
let post = DbPost {
2022-06-02 16:47:12 +05:30
text: apub.content,
ap_id: apub.id,
creator: apub.attributed_to,
local: false,
};
let mut lock = data.posts.lock().unwrap();
lock.push(post.clone());
Ok(post)
}
}