2024-04-29 21:58:08 +02:00
|
|
|
use std::{collections::BTreeSet, sync::Arc};
|
2024-04-09 01:14:48 +02:00
|
|
|
|
|
|
|
use openssl::rsa::Rsa;
|
2024-04-29 22:02:18 +02:00
|
|
|
use sea_orm::{ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, QuerySelect, SelectColumns, Set};
|
2024-04-09 01:14:48 +02:00
|
|
|
|
2024-05-11 22:47:29 +02:00
|
|
|
use crate::{config::Config, model, server::fetcher::Fetcher};
|
2024-04-09 01:14:48 +02:00
|
|
|
|
2024-04-18 05:25:56 +02:00
|
|
|
use super::dispatcher::Dispatcher;
|
2024-04-09 01:14:48 +02:00
|
|
|
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct Context(Arc<ContextInner>);
|
|
|
|
struct ContextInner {
|
|
|
|
db: DatabaseConnection,
|
2024-05-11 22:47:29 +02:00
|
|
|
config: Config,
|
2024-04-09 01:14:48 +02:00
|
|
|
domain: String,
|
|
|
|
protocol: String,
|
|
|
|
dispatcher: Dispatcher,
|
|
|
|
// TODO keep these pre-parsed
|
|
|
|
app: model::application::Model,
|
2024-04-29 21:58:08 +02:00
|
|
|
relays: BTreeSet<String>,
|
2024-04-09 01:14:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[macro_export]
|
|
|
|
macro_rules! url {
|
|
|
|
($ctx:expr, $($args: tt)*) => {
|
2024-04-20 04:26:16 +02:00
|
|
|
format!("{}{}{}", $ctx.protocol(), $ctx.domain(), format!($($args)*))
|
2024-04-09 01:14:48 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Context {
|
|
|
|
|
|
|
|
// TODO slim constructor down, maybe make a builder?
|
2024-05-11 22:47:29 +02:00
|
|
|
pub async fn new(db: DatabaseConnection, mut domain: String, config: Config) -> crate::Result<Self> {
|
2024-04-09 01:14:48 +02:00
|
|
|
let protocol = if domain.starts_with("http://")
|
|
|
|
{ "http://" } else { "https://" }.to_string();
|
|
|
|
if domain.ends_with('/') {
|
|
|
|
domain.replace_range(domain.len()-1.., "");
|
|
|
|
}
|
|
|
|
if domain.starts_with("http") {
|
|
|
|
domain = domain.replace("https://", "").replace("http://", "");
|
|
|
|
}
|
2024-04-13 00:44:53 +02:00
|
|
|
let dispatcher = Dispatcher::default();
|
2024-04-09 01:14:48 +02:00
|
|
|
for _ in 0..1 { // TODO customize delivery workers amount
|
|
|
|
dispatcher.spawn(db.clone(), domain.clone(), 30); // TODO ew don't do it this deep and secretly!!
|
|
|
|
}
|
|
|
|
let app = match model::application::Entity::find().one(&db).await? {
|
|
|
|
Some(model) => model,
|
|
|
|
None => {
|
|
|
|
tracing::info!("generating application keys");
|
|
|
|
let rsa = Rsa::generate(2048)?;
|
|
|
|
let privk = std::str::from_utf8(&rsa.private_key_to_pem()?)?.to_string();
|
|
|
|
let pubk = std::str::from_utf8(&rsa.public_key_to_pem()?)?.to_string();
|
|
|
|
let system = model::application::ActiveModel {
|
|
|
|
id: sea_orm::ActiveValue::NotSet,
|
|
|
|
private_key: sea_orm::ActiveValue::Set(privk.clone()),
|
|
|
|
public_key: sea_orm::ActiveValue::Set(pubk.clone()),
|
|
|
|
created: sea_orm::ActiveValue::Set(chrono::Utc::now()),
|
|
|
|
};
|
|
|
|
model::application::Entity::insert(system).exec(&db).await?;
|
|
|
|
// sqlite doesn't resurn last inserted id so we're better off just querying again, it's just one time
|
|
|
|
model::application::Entity::find().one(&db).await?.expect("could not find app config just inserted")
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-04-29 21:58:08 +02:00
|
|
|
let relays = model::relay::Entity::find()
|
|
|
|
.select_only()
|
|
|
|
.select_column(model::relay::Column::Id)
|
|
|
|
.filter(model::relay::Column::Accepted.eq(true))
|
|
|
|
.into_tuple::<String>()
|
|
|
|
.all(&db)
|
|
|
|
.await?;
|
|
|
|
|
2024-04-09 01:14:48 +02:00
|
|
|
Ok(Context(Arc::new(ContextInner {
|
2024-05-11 22:47:29 +02:00
|
|
|
db, domain, protocol, app, dispatcher, config,
|
2024-04-29 21:58:08 +02:00
|
|
|
relays: BTreeSet::from_iter(relays.into_iter()),
|
2024-04-09 01:14:48 +02:00
|
|
|
})))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn app(&self) -> &model::application::Model {
|
|
|
|
&self.0.app
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn db(&self) -> &DatabaseConnection {
|
|
|
|
&self.0.db
|
|
|
|
}
|
|
|
|
|
2024-05-11 22:47:29 +02:00
|
|
|
pub fn cfg(&self) -> &Config {
|
|
|
|
&self.0.config
|
|
|
|
}
|
|
|
|
|
2024-04-20 04:26:16 +02:00
|
|
|
pub fn domain(&self) -> &str {
|
2024-04-09 01:14:48 +02:00
|
|
|
&self.0.domain
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn protocol(&self) -> &str {
|
|
|
|
&self.0.protocol
|
|
|
|
}
|
|
|
|
|
2024-04-20 04:26:16 +02:00
|
|
|
pub fn base(&self) -> String {
|
2024-04-23 05:30:10 +02:00
|
|
|
format!("{}{}", self.0.protocol, self.0.domain)
|
2024-04-20 04:26:16 +02:00
|
|
|
}
|
|
|
|
|
2024-04-09 01:14:48 +02:00
|
|
|
pub fn uri(&self, entity: &str, id: String) -> String {
|
2024-04-30 01:48:30 +02:00
|
|
|
if id.starts_with("http") { // ready-to-use id
|
|
|
|
id
|
|
|
|
} else if id.starts_with('+') { // compacted id
|
2024-05-13 15:07:58 +02:00
|
|
|
// TODO theres already 2 edge cases, i really need to get rid of this
|
|
|
|
id
|
2024-04-30 01:48:30 +02:00
|
|
|
.replace('@', "/")
|
2024-05-13 17:17:19 +02:00
|
|
|
.replace("///", "/@/") // omg wordpress PLEASE AAAAAAAAAAAAAAAAAAAA
|
2024-04-30 01:48:30 +02:00
|
|
|
.replace("//", "/@") // oops my method sucks!! TODO
|
2024-05-13 15:07:58 +02:00
|
|
|
.replacen('+', "https://", 1)
|
2024-05-13 18:54:09 +02:00
|
|
|
.replace(' ', "%20") // omg wordpress
|
2024-04-30 01:48:30 +02:00
|
|
|
} else { // bare local id
|
2024-04-09 01:14:48 +02:00
|
|
|
format!("{}{}/{}/{}", self.0.protocol, self.0.domain, entity, id)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-20 01:57:22 +02:00
|
|
|
/// get bare id, usually an uuid but unspecified
|
|
|
|
pub fn id(&self, uri: &str) -> String {
|
|
|
|
if uri.starts_with(&self.0.domain) {
|
|
|
|
uri.split('/').last().unwrap_or("").to_string()
|
|
|
|
} else {
|
|
|
|
uri
|
|
|
|
.replace("https://", "+")
|
|
|
|
.replace("http://", "+")
|
|
|
|
.replace('/', "@")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-09 01:14:48 +02:00
|
|
|
/// get full user id uri
|
|
|
|
pub fn uid(&self, id: String) -> String {
|
|
|
|
self.uri("users", id)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// get full object id uri
|
|
|
|
pub fn oid(&self, id: String) -> String {
|
|
|
|
self.uri("objects", id)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// get full activity id uri
|
|
|
|
pub fn aid(&self, id: String) -> String {
|
|
|
|
self.uri("activities", id)
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
pub fn server(id: &str) -> String {
|
|
|
|
id
|
|
|
|
.replace("https://", "")
|
|
|
|
.replace("http://", "")
|
|
|
|
.split('/')
|
|
|
|
.next()
|
|
|
|
.unwrap_or("")
|
|
|
|
.to_string()
|
|
|
|
}
|
|
|
|
|
2024-04-12 18:40:24 +02:00
|
|
|
pub fn is_local(&self, id: &str) -> bool {
|
|
|
|
// TODO consider precalculating once this format!
|
|
|
|
id.starts_with(&format!("{}{}", self.0.protocol, self.0.domain))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn expand_addressing(&self, targets: Vec<String>) -> crate::Result<Vec<String>> {
|
|
|
|
let mut out = Vec::new();
|
|
|
|
for target in targets {
|
|
|
|
if target.ends_with("/followers") {
|
|
|
|
let target_id = target.replace("/followers", "");
|
|
|
|
model::relation::Entity::find()
|
2024-04-19 03:28:39 +02:00
|
|
|
.filter(model::relation::Column::Following.eq(target_id))
|
2024-04-12 18:40:24 +02:00
|
|
|
.select_only()
|
|
|
|
.select_column(model::relation::Column::Follower)
|
|
|
|
.into_tuple::<String>()
|
|
|
|
.all(self.db())
|
|
|
|
.await?
|
|
|
|
.into_iter()
|
|
|
|
.for_each(|x| out.push(x));
|
|
|
|
} else {
|
|
|
|
out.push(target);
|
|
|
|
}
|
2024-04-09 01:14:48 +02:00
|
|
|
}
|
2024-04-12 18:40:24 +02:00
|
|
|
Ok(out)
|
2024-04-09 01:14:48 +02:00
|
|
|
}
|
|
|
|
|
2024-04-21 15:41:29 +02:00
|
|
|
pub async fn address_to(&self, aid: Option<&str>, oid: Option<&str>, targets: &[String]) -> crate::Result<()> {
|
|
|
|
let local_activity = aid.map(|x| self.is_local(x)).unwrap_or(false);
|
|
|
|
let local_object = oid.map(|x| self.is_local(x)).unwrap_or(false);
|
2024-04-09 01:14:48 +02:00
|
|
|
let addressings : Vec<model::addressing::ActiveModel> = targets
|
|
|
|
.iter()
|
|
|
|
.filter(|to| !to.is_empty())
|
|
|
|
.filter(|to| !to.ends_with("/followers"))
|
2024-04-21 15:41:29 +02:00
|
|
|
.filter(|to| local_activity || local_object || to.as_str() == apb::target::PUBLIC || self.is_local(to))
|
2024-04-09 01:14:48 +02:00
|
|
|
.map(|to| model::addressing::ActiveModel {
|
|
|
|
id: sea_orm::ActiveValue::NotSet,
|
|
|
|
server: Set(Context::server(to)),
|
|
|
|
actor: Set(to.to_string()),
|
2024-04-21 15:41:29 +02:00
|
|
|
activity: Set(aid.map(|x| x.to_string())),
|
2024-04-09 01:14:48 +02:00
|
|
|
object: Set(oid.map(|x| x.to_string())),
|
|
|
|
published: Set(chrono::Utc::now()),
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
if !addressings.is_empty() {
|
|
|
|
model::addressing::Entity::insert_many(addressings)
|
|
|
|
.exec(self.db())
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn deliver_to(&self, aid: &str, from: &str, targets: &[String]) -> crate::Result<()> {
|
2024-04-18 07:02:42 +02:00
|
|
|
let mut deliveries = Vec::new();
|
|
|
|
for target in targets.iter()
|
2024-04-09 01:14:48 +02:00
|
|
|
.filter(|to| !to.is_empty())
|
2024-04-20 04:26:16 +02:00
|
|
|
.filter(|to| Context::server(to) != self.domain())
|
2024-04-11 00:29:32 +02:00
|
|
|
.filter(|to| to != &apb::target::PUBLIC)
|
2024-04-18 07:02:42 +02:00
|
|
|
{
|
|
|
|
// TODO fetch concurrently
|
|
|
|
match self.fetch_user(target).await {
|
|
|
|
Ok(model::user::Model { inbox: Some(inbox), .. }) => deliveries.push(
|
|
|
|
model::delivery::ActiveModel {
|
|
|
|
id: sea_orm::ActiveValue::NotSet,
|
|
|
|
actor: Set(from.to_string()),
|
|
|
|
// TODO we should resolve each user by id and check its inbox because we can't assume
|
|
|
|
// it's /users/{id}/inbox for every software, but oh well it's waaaaay easier now
|
|
|
|
target: Set(inbox),
|
|
|
|
activity: Set(aid.to_string()),
|
|
|
|
created: Set(chrono::Utc::now()),
|
|
|
|
not_before: Set(chrono::Utc::now()),
|
|
|
|
attempt: Set(0),
|
|
|
|
}
|
|
|
|
),
|
|
|
|
Ok(_) => tracing::error!("resolved target but missing inbox: '{target}', skipping delivery"),
|
|
|
|
Err(e) => tracing::error!("failed resolving target inbox: {e}, skipping delivery to '{target}'"),
|
|
|
|
}
|
|
|
|
}
|
2024-04-09 01:14:48 +02:00
|
|
|
|
|
|
|
if !deliveries.is_empty() {
|
|
|
|
model::delivery::Entity::insert_many(deliveries)
|
|
|
|
.exec(self.db())
|
|
|
|
.await?;
|
|
|
|
}
|
|
|
|
|
|
|
|
self.0.dispatcher.wakeup();
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn dispatch(&self, uid: &str, activity_targets: Vec<String>, aid: &str, oid: Option<&str>) -> crate::Result<()> {
|
2024-04-12 18:40:24 +02:00
|
|
|
let addressed = self.expand_addressing(activity_targets).await?;
|
2024-04-21 15:41:29 +02:00
|
|
|
self.address_to(Some(aid), oid, &addressed).await?;
|
2024-04-09 01:14:48 +02:00
|
|
|
self.deliver_to(aid, uid, &addressed).await?;
|
|
|
|
Ok(())
|
|
|
|
}
|
2024-04-29 21:58:08 +02:00
|
|
|
|
|
|
|
pub fn is_relay(&self, id: &str) -> bool {
|
|
|
|
self.0.relays.contains(id)
|
|
|
|
}
|
2024-04-09 01:14:48 +02:00
|
|
|
}
|