mirror of
https://github.com/Nutomic/ibis.git
synced 2024-11-22 07:31:09 +00:00
import apub lib example with some adjustments
This commit is contained in:
parent
6686088f76
commit
79df3f3837
15 changed files with 2634 additions and 4 deletions
1920
Cargo.lock
generated
1920
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
16
Cargo.toml
16
Cargo.toml
|
@ -3,6 +3,18 @@ name = "fediwiki"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
activitypub_federation = { version = "0.4.7", features = ["axum"], default-features = false }
|
||||||
|
anyhow = "1.0.75"
|
||||||
|
async-trait = "0.1.74"
|
||||||
|
axum = "0.6.20"
|
||||||
|
axum-macros = "0.3.8"
|
||||||
|
chrono = "0.4.31"
|
||||||
|
enum_delegate = "0.2.0"
|
||||||
|
env_logger = { version = "0.10.1", default-features = false }
|
||||||
|
rand = "0.8.5"
|
||||||
|
serde = "1.0.192"
|
||||||
|
serde_json = "1.0.108"
|
||||||
|
tokio = { version = "1.34.0", features = ["full"] }
|
||||||
|
tracing = "0.1.40"
|
||||||
|
url = "2.4.1"
|
||||||
|
|
49
src/activities/accept.rs
Normal file
49
src/activities/accept.rs
Normal file
|
@ -0,0 +1,49 @@
|
||||||
|
use crate::{activities::follow::Follow, instance::DatabaseHandle, objects::person::DbUser};
|
||||||
|
use activitypub_federation::{
|
||||||
|
config::Data, fetch::object_id::ObjectId, kinds::activity::AcceptType, traits::ActivityHandler,
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Accept {
|
||||||
|
actor: ObjectId<DbUser>,
|
||||||
|
object: Follow,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
kind: AcceptType,
|
||||||
|
id: Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Accept {
|
||||||
|
pub fn new(actor: ObjectId<DbUser>, object: Follow, id: Url) -> Accept {
|
||||||
|
Accept {
|
||||||
|
actor,
|
||||||
|
object,
|
||||||
|
kind: Default::default(),
|
||||||
|
id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl ActivityHandler for Accept {
|
||||||
|
type DataType = DatabaseHandle;
|
||||||
|
type Error = crate::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> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
62
src/activities/create_post.rs
Normal file
62
src/activities/create_post.rs
Normal file
|
@ -0,0 +1,62 @@
|
||||||
|
use crate::{
|
||||||
|
instance::DatabaseHandle,
|
||||||
|
objects::{person::DbUser, post::Note},
|
||||||
|
DbPost,
|
||||||
|
};
|
||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::object_id::ObjectId,
|
||||||
|
kinds::activity::CreateType,
|
||||||
|
protocol::helpers::deserialize_one_or_many,
|
||||||
|
traits::{ActivityHandler, Object},
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct CreatePost {
|
||||||
|
pub(crate) actor: ObjectId<DbUser>,
|
||||||
|
#[serde(deserialize_with = "deserialize_one_or_many")]
|
||||||
|
pub(crate) to: Vec<Url>,
|
||||||
|
pub(crate) object: Note,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub(crate) kind: CreateType,
|
||||||
|
pub(crate) id: Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CreatePost {
|
||||||
|
pub fn new(note: Note, id: Url) -> CreatePost {
|
||||||
|
CreatePost {
|
||||||
|
actor: note.attributed_to.clone(),
|
||||||
|
to: note.to.clone(),
|
||||||
|
object: note,
|
||||||
|
kind: CreateType::Create,
|
||||||
|
id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl ActivityHandler for CreatePost {
|
||||||
|
type DataType = DatabaseHandle;
|
||||||
|
type Error = crate::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> {
|
||||||
|
DbPost::verify(&self.object, &self.id, data).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
DbPost::from_json(self.object, data).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
72
src/activities/follow.rs
Normal file
72
src/activities/follow.rs
Normal file
|
@ -0,0 +1,72 @@
|
||||||
|
use crate::{
|
||||||
|
activities::accept::Accept, generate_object_id, instance::DatabaseHandle,
|
||||||
|
objects::person::DbUser,
|
||||||
|
};
|
||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::object_id::ObjectId,
|
||||||
|
kinds::activity::FollowType,
|
||||||
|
traits::{ActivityHandler, Actor},
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Follow {
|
||||||
|
pub(crate) actor: ObjectId<DbUser>,
|
||||||
|
pub(crate) object: ObjectId<DbUser>,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
kind: FollowType,
|
||||||
|
id: Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Follow {
|
||||||
|
pub fn new(actor: ObjectId<DbUser>, object: ObjectId<DbUser>, id: Url) -> Follow {
|
||||||
|
Follow {
|
||||||
|
actor,
|
||||||
|
object,
|
||||||
|
kind: Default::default(),
|
||||||
|
id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl ActivityHandler for Follow {
|
||||||
|
type DataType = DatabaseHandle;
|
||||||
|
type Error = crate::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> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ignore clippy false positive: https://github.com/rust-lang/rust-clippy/issues/6446
|
||||||
|
#[allow(clippy::await_holding_lock)]
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
// add to followers
|
||||||
|
let local_user = {
|
||||||
|
let mut users = data.users.lock().unwrap();
|
||||||
|
let local_user = users.first_mut().unwrap();
|
||||||
|
local_user.followers.push(self.actor.inner().clone());
|
||||||
|
local_user.clone()
|
||||||
|
};
|
||||||
|
|
||||||
|
// send back an accept
|
||||||
|
let follower = self.actor.dereference(data).await?;
|
||||||
|
let id = generate_object_id(data.domain())?;
|
||||||
|
let accept = Accept::new(local_user.ap_id.clone(), self, id.clone());
|
||||||
|
local_user
|
||||||
|
.send(accept, vec![follower.shared_inbox_or_inbox()], data)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
3
src/activities/mod.rs
Normal file
3
src/activities/mod.rs
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
pub mod accept;
|
||||||
|
pub mod create_post;
|
||||||
|
pub mod follow;
|
85
src/axum/http.rs
Normal file
85
src/axum/http.rs
Normal file
|
@ -0,0 +1,85 @@
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::{
|
||||||
|
instance::DatabaseHandle,
|
||||||
|
objects::person::{DbUser, Person, PersonAcceptedActivities},
|
||||||
|
};
|
||||||
|
use activitypub_federation::{
|
||||||
|
axum::{
|
||||||
|
inbox::{receive_activity, ActivityData},
|
||||||
|
json::FederationJson,
|
||||||
|
},
|
||||||
|
config::{Data, FederationConfig, FederationMiddleware},
|
||||||
|
fetch::webfinger::{build_webfinger_response, extract_webfinger_name, Webfinger},
|
||||||
|
protocol::context::WithContext,
|
||||||
|
traits::Object,
|
||||||
|
};
|
||||||
|
use axum::{
|
||||||
|
extract::{Path, Query},
|
||||||
|
response::IntoResponse,
|
||||||
|
routing::{get, post},
|
||||||
|
Json, Router,
|
||||||
|
};
|
||||||
|
use axum_macros::debug_handler;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use std::net::ToSocketAddrs;
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
|
pub fn listen(config: &FederationConfig<DatabaseHandle>) -> Result<(), Error> {
|
||||||
|
let hostname = config.domain();
|
||||||
|
info!("Listening with axum on {hostname}");
|
||||||
|
let config = config.clone();
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/:user/inbox", post(http_post_user_inbox))
|
||||||
|
.route("/:user", get(http_get_user))
|
||||||
|
.route("/.well-known/webfinger", get(webfinger))
|
||||||
|
.layer(FederationMiddleware::new(config));
|
||||||
|
|
||||||
|
let addr = hostname
|
||||||
|
.to_socket_addrs()?
|
||||||
|
.next()
|
||||||
|
.expect("Failed to lookup domain name");
|
||||||
|
let server = axum::Server::bind(&addr).serve(app.into_make_service());
|
||||||
|
|
||||||
|
tokio::spawn(server);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[debug_handler]
|
||||||
|
async fn http_get_user(
|
||||||
|
Path(name): Path<String>,
|
||||||
|
data: Data<DatabaseHandle>,
|
||||||
|
) -> Result<FederationJson<WithContext<Person>>, Error> {
|
||||||
|
let db_user = data.read_user(&name)?;
|
||||||
|
let json_user = db_user.into_json(&data).await?;
|
||||||
|
Ok(FederationJson(WithContext::new_default(json_user)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[debug_handler]
|
||||||
|
async fn http_post_user_inbox(
|
||||||
|
data: Data<DatabaseHandle>,
|
||||||
|
activity_data: ActivityData,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
receive_activity::<WithContext<PersonAcceptedActivities>, DbUser, DatabaseHandle>(
|
||||||
|
activity_data,
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct WebfingerQuery {
|
||||||
|
resource: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[debug_handler]
|
||||||
|
async fn webfinger(
|
||||||
|
Query(query): Query<WebfingerQuery>,
|
||||||
|
data: Data<DatabaseHandle>,
|
||||||
|
) -> Result<Json<Webfinger>, Error> {
|
||||||
|
let name = extract_webfinger_name(&query.resource, &data)?;
|
||||||
|
let db_user = data.read_user(&name)?;
|
||||||
|
Ok(Json(build_webfinger_response(
|
||||||
|
query.resource,
|
||||||
|
db_user.ap_id.into_inner(),
|
||||||
|
)))
|
||||||
|
}
|
12
src/axum/mod.rs
Normal file
12
src/axum/mod.rs
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
use crate::error::Error;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
|
||||||
|
#[allow(clippy::diverging_sub_expression, clippy::items_after_statements)]
|
||||||
|
pub mod http;
|
||||||
|
|
||||||
|
impl IntoResponse for Error {
|
||||||
|
fn into_response(self) -> Response {
|
||||||
|
(StatusCode::INTERNAL_SERVER_ERROR, format!("{}", self.0)).into_response()
|
||||||
|
}
|
||||||
|
}
|
19
src/error.rs
Normal file
19
src/error.rs
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
use std::fmt::{Display, Formatter};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Error(pub(crate) anyhow::Error);
|
||||||
|
|
||||||
|
impl Display for Error {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
|
std::fmt::Display::fmt(&self.0, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> From<T> for Error
|
||||||
|
where
|
||||||
|
T: Into<anyhow::Error>,
|
||||||
|
{
|
||||||
|
fn from(t: T) -> Self {
|
||||||
|
Error(t.into())
|
||||||
|
}
|
||||||
|
}
|
70
src/instance.rs
Normal file
70
src/instance.rs
Normal file
|
@ -0,0 +1,70 @@
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::objects::{person::DbUser, post::DbPost};
|
||||||
|
use activitypub_federation::config::{FederationConfig, UrlVerifier};
|
||||||
|
use anyhow::anyhow;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
pub async fn new_instance(
|
||||||
|
hostname: &str,
|
||||||
|
name: String,
|
||||||
|
) -> Result<FederationConfig<DatabaseHandle>, Error> {
|
||||||
|
let mut system_user = DbUser::new(hostname, "system".into())?;
|
||||||
|
system_user.ap_id = Url::parse(&format!("http://{}/", hostname))?.into();
|
||||||
|
|
||||||
|
let local_user = DbUser::new(hostname, name)?;
|
||||||
|
let database = Arc::new(Database {
|
||||||
|
system_user: system_user.clone(),
|
||||||
|
users: Mutex::new(vec![local_user]),
|
||||||
|
posts: Mutex::new(vec![]),
|
||||||
|
});
|
||||||
|
let config = FederationConfig::builder()
|
||||||
|
.domain(hostname)
|
||||||
|
.signed_fetch_actor(&system_user)
|
||||||
|
.app_data(database)
|
||||||
|
.debug(true)
|
||||||
|
.build()
|
||||||
|
.await?;
|
||||||
|
Ok(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type DatabaseHandle = Arc<Database>;
|
||||||
|
|
||||||
|
/// Our "database" which contains all known posts and users (local and federated)
|
||||||
|
pub struct Database {
|
||||||
|
pub system_user: DbUser,
|
||||||
|
pub users: Mutex<Vec<DbUser>>,
|
||||||
|
pub posts: Mutex<Vec<DbPost>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Use this to store your federation blocklist, or a database connection needed to retrieve it.
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct MyUrlVerifier();
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl UrlVerifier for MyUrlVerifier {
|
||||||
|
async fn verify(&self, url: &Url) -> Result<(), &'static str> {
|
||||||
|
if url.domain() == Some("malicious.com") {
|
||||||
|
Err("malicious domain")
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Database {
|
||||||
|
pub fn local_user(&self) -> DbUser {
|
||||||
|
let lock = self.users.lock().unwrap();
|
||||||
|
lock.first().unwrap().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_user(&self, name: &str) -> Result<DbUser, Error> {
|
||||||
|
let db_user = self.local_user();
|
||||||
|
if name == db_user.name {
|
||||||
|
Ok(db_user)
|
||||||
|
} else {
|
||||||
|
Err(anyhow!("Invalid user {name}").into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
26
src/main.rs
26
src/main.rs
|
@ -1,3 +1,25 @@
|
||||||
fn main() {
|
use crate::axum::http::listen;
|
||||||
println!("Hello, world!");
|
use crate::{instance::new_instance, objects::post::DbPost, utils::generate_object_id};
|
||||||
|
use error::Error;
|
||||||
|
use tracing::log::LevelFilter;
|
||||||
|
|
||||||
|
mod activities;
|
||||||
|
mod axum;
|
||||||
|
mod error;
|
||||||
|
mod instance;
|
||||||
|
mod objects;
|
||||||
|
mod utils;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Error> {
|
||||||
|
env_logger::builder()
|
||||||
|
.filter_level(LevelFilter::Warn)
|
||||||
|
.filter_module("activitypub_federation", LevelFilter::Info)
|
||||||
|
.filter_module("fediwiki", LevelFilter::Info)
|
||||||
|
.init();
|
||||||
|
|
||||||
|
let alpha = new_instance("localhost:8001", "alpha".to_string()).await?;
|
||||||
|
listen(&alpha)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
2
src/objects/mod.rs
Normal file
2
src/objects/mod.rs
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
pub mod person;
|
||||||
|
pub mod post;
|
195
src/objects/person.rs
Normal file
195
src/objects/person.rs
Normal file
|
@ -0,0 +1,195 @@
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::{
|
||||||
|
activities::{accept::Accept, create_post::CreatePost, follow::Follow},
|
||||||
|
instance::DatabaseHandle,
|
||||||
|
objects::post::DbPost,
|
||||||
|
utils::generate_object_id,
|
||||||
|
};
|
||||||
|
use activitypub_federation::{
|
||||||
|
activity_queue::send_activity,
|
||||||
|
config::Data,
|
||||||
|
fetch::{object_id::ObjectId, webfinger::webfinger_resolve_actor},
|
||||||
|
http_signatures::generate_actor_keypair,
|
||||||
|
kinds::actor::PersonType,
|
||||||
|
protocol::{context::WithContext, public_key::PublicKey, verification::verify_domains_match},
|
||||||
|
traits::{ActivityHandler, Actor, Object},
|
||||||
|
};
|
||||||
|
use chrono::{Local, NaiveDateTime};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::fmt::Debug;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DbUser {
|
||||||
|
pub name: String,
|
||||||
|
pub ap_id: ObjectId<DbUser>,
|
||||||
|
pub inbox: Url,
|
||||||
|
// exists for all users (necessary to verify http signatures)
|
||||||
|
public_key: String,
|
||||||
|
// exists only for local users
|
||||||
|
private_key: Option<String>,
|
||||||
|
last_refreshed_at: NaiveDateTime,
|
||||||
|
pub followers: Vec<Url>,
|
||||||
|
pub local: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// List of all activities which this actor can receive.
|
||||||
|
#[derive(Deserialize, Serialize, Debug)]
|
||||||
|
#[serde(untagged)]
|
||||||
|
#[enum_delegate::implement(ActivityHandler)]
|
||||||
|
pub enum PersonAcceptedActivities {
|
||||||
|
Follow(Follow),
|
||||||
|
Accept(Accept),
|
||||||
|
CreateNote(CreatePost),
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
ap_id,
|
||||||
|
inbox,
|
||||||
|
public_key: keypair.public_key,
|
||||||
|
private_key: Some(keypair.private_key),
|
||||||
|
last_refreshed_at: Local::now().naive_local(),
|
||||||
|
followers: vec![],
|
||||||
|
local: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Person {
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
kind: PersonType,
|
||||||
|
preferred_username: String,
|
||||||
|
id: ObjectId<DbUser>,
|
||||||
|
inbox: Url,
|
||||||
|
public_key: PublicKey,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DbUser {
|
||||||
|
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()))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn follow(&self, other: &str, data: &Data<DatabaseHandle>) -> Result<(), Error> {
|
||||||
|
let other: DbUser = webfinger_resolve_actor(other, data).await?;
|
||||||
|
let id = generate_object_id(data.domain())?;
|
||||||
|
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?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn post(&self, post: DbPost, data: &Data<DatabaseHandle>) -> Result<(), Error> {
|
||||||
|
let id = generate_object_id(data.domain())?;
|
||||||
|
let create = CreatePost::new(post.into_json(data).await?, id.clone());
|
||||||
|
let mut inboxes = vec![];
|
||||||
|
for f in self.followers.clone() {
|
||||||
|
let user: DbUser = ObjectId::from(f).dereference(data).await?;
|
||||||
|
inboxes.push(user.shared_inbox_or_inbox());
|
||||||
|
}
|
||||||
|
self.send(create, inboxes, data).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn send<Activity>(
|
||||||
|
&self,
|
||||||
|
activity: Activity,
|
||||||
|
recipients: Vec<Url>,
|
||||||
|
data: &Data<DatabaseHandle>,
|
||||||
|
) -> Result<(), <Activity as ActivityHandler>::Error>
|
||||||
|
where
|
||||||
|
Activity: ActivityHandler + Serialize + Debug + Send + Sync,
|
||||||
|
<Activity as ActivityHandler>::Error: From<anyhow::Error> + From<serde_json::Error>,
|
||||||
|
{
|
||||||
|
let activity = WithContext::new_default(activity);
|
||||||
|
send_activity(activity, self, recipients, data).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Object for DbUser {
|
||||||
|
type DataType = DatabaseHandle;
|
||||||
|
type Kind = Person;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
|
||||||
|
Some(self.last_refreshed_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_from_id(
|
||||||
|
object_id: Url,
|
||||||
|
data: &Data<Self::DataType>,
|
||||||
|
) -> 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_json(self, _data: &Data<Self::DataType>) -> Result<Self::Kind, Self::Error> {
|
||||||
|
Ok(Person {
|
||||||
|
preferred_username: self.name.clone(),
|
||||||
|
kind: Default::default(),
|
||||||
|
id: self.ap_id.clone(),
|
||||||
|
inbox: self.inbox.clone(),
|
||||||
|
public_key: self.public_key(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(
|
||||||
|
json: &Self::Kind,
|
||||||
|
expected_domain: &Url,
|
||||||
|
_data: &Data<Self::DataType>,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
verify_domains_match(json.id.inner(), expected_domain)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn from_json(json: Self::Kind, data: &Data<Self::DataType>) -> Result<Self, Self::Error> {
|
||||||
|
let user = DbUser {
|
||||||
|
name: json.preferred_username,
|
||||||
|
ap_id: json.id,
|
||||||
|
inbox: json.inbox,
|
||||||
|
public_key: json.public_key.public_key_pem,
|
||||||
|
private_key: None,
|
||||||
|
last_refreshed_at: Local::now().naive_local(),
|
||||||
|
followers: vec![],
|
||||||
|
local: false,
|
||||||
|
};
|
||||||
|
let mut mutex = data.users.lock().unwrap();
|
||||||
|
mutex.push(user.clone());
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Actor for DbUser {
|
||||||
|
fn id(&self) -> Url {
|
||||||
|
self.ap_id.inner().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn public_key_pem(&self) -> &str {
|
||||||
|
&self.public_key
|
||||||
|
}
|
||||||
|
|
||||||
|
fn private_key_pem(&self) -> Option<String> {
|
||||||
|
self.private_key.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inbox(&self) -> Url {
|
||||||
|
self.inbox.clone()
|
||||||
|
}
|
||||||
|
}
|
94
src/objects/post.rs
Normal file
94
src/objects/post.rs
Normal file
|
@ -0,0 +1,94 @@
|
||||||
|
use crate::{error::Error, generate_object_id, instance::DatabaseHandle, objects::person::DbUser};
|
||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::object_id::ObjectId,
|
||||||
|
kinds::{object::NoteType, public},
|
||||||
|
protocol::{helpers::deserialize_one_or_many, verification::verify_domains_match},
|
||||||
|
traits::Object,
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct DbPost {
|
||||||
|
pub text: String,
|
||||||
|
pub ap_id: ObjectId<DbPost>,
|
||||||
|
pub creator: ObjectId<DbUser>,
|
||||||
|
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 {
|
||||||
|
text,
|
||||||
|
ap_id,
|
||||||
|
creator,
|
||||||
|
local: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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>,
|
||||||
|
#[serde(deserialize_with = "deserialize_one_or_many")]
|
||||||
|
pub(crate) to: Vec<Url>,
|
||||||
|
content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Object for DbPost {
|
||||||
|
type DataType = DatabaseHandle;
|
||||||
|
type Kind = Note;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
async fn read_from_id(
|
||||||
|
object_id: Url,
|
||||||
|
data: &Data<Self::DataType>,
|
||||||
|
) -> Result<Option<Self>, Self::Error> {
|
||||||
|
let posts = data.posts.lock().unwrap();
|
||||||
|
let res = posts
|
||||||
|
.clone()
|
||||||
|
.into_iter()
|
||||||
|
.find(|u| u.ap_id.inner() == &object_id);
|
||||||
|
Ok(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn into_json(self, data: &Data<Self::DataType>) -> Result<Self::Kind, Self::Error> {
|
||||||
|
let creator = self.creator.dereference_local(data).await?;
|
||||||
|
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(
|
||||||
|
json: &Self::Kind,
|
||||||
|
expected_domain: &Url,
|
||||||
|
_data: &Data<Self::DataType>,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
verify_domains_match(json.id.inner(), expected_domain)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn from_json(json: Self::Kind, data: &Data<Self::DataType>) -> Result<Self, Self::Error> {
|
||||||
|
let post = DbPost {
|
||||||
|
text: json.content,
|
||||||
|
ap_id: json.id,
|
||||||
|
creator: json.attributed_to,
|
||||||
|
local: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut lock = data.posts.lock().unwrap();
|
||||||
|
lock.push(post.clone());
|
||||||
|
Ok(post)
|
||||||
|
}
|
||||||
|
}
|
13
src/utils.rs
Normal file
13
src/utils.rs
Normal file
|
@ -0,0 +1,13 @@
|
||||||
|
use rand::{distributions::Alphanumeric, thread_rng, Rng};
|
||||||
|
use url::{ParseError, Url};
|
||||||
|
|
||||||
|
/// Just generate random url as object id. In a real project, you probably want to use
|
||||||
|
/// an url which contains the database id for easy retrieval (or store the random id in db).
|
||||||
|
pub fn generate_object_id(domain: &str) -> Result<Url, ParseError> {
|
||||||
|
let id: String = thread_rng()
|
||||||
|
.sample_iter(&Alphanumeric)
|
||||||
|
.take(7)
|
||||||
|
.map(char::from)
|
||||||
|
.collect();
|
||||||
|
Url::parse(&format!("http://{}/objects/{}", domain, id))
|
||||||
|
}
|
Loading…
Reference in a new issue