Update activitystreams

This commit is contained in:
asonix
2020-06-19 23:11:02 -05:00
parent e65c21582c
commit 2bbcc82d9c
27 changed files with 334 additions and 366 deletions
+5 -6
View File
@@ -1,5 +1,5 @@
use crate::{data::ActorCache, error::MyError, middleware::MyVerify, requests::Requests};
use activitystreams_new::{primitives::XsdAnyUri, uri};
use activitystreams_new::{uri, url::Url};
use config::Environment;
use http_signature_normalization_actix::prelude::{VerifyDigest, VerifySignature};
use sha2::{Digest, Sha256};
@@ -33,7 +33,7 @@ pub struct Config {
pretty_log: bool,
publish_blocks: bool,
max_connections: usize,
base_uri: XsdAnyUri,
base_uri: Url,
}
pub enum UrlKind {
@@ -157,9 +157,8 @@ impl Config {
"https://git.asonix.dog/asonix/ap-relay".to_owned()
}
pub fn generate_url(&self, kind: UrlKind) -> XsdAnyUri {
let mut uri = self.base_uri.clone();
let url = uri.as_url_mut();
pub fn generate_url(&self, kind: UrlKind) -> Url {
let mut url = self.base_uri.clone();
match kind {
UrlKind::Activity => url.set_path(&format!("activity/{}", Uuid::new_v4())),
@@ -177,6 +176,6 @@ impl Config {
UrlKind::Outbox => url.set_path("outbox"),
};
uri
url
}
}
+25 -52
View File
@@ -1,5 +1,5 @@
use crate::{apub::AcceptedActors, db::Db, error::MyError, requests::Requests};
use activitystreams_new::{prelude::*, primitives::XsdAnyUri, uri};
use activitystreams_new::{prelude::*, primitives::XsdAnyUri, uri, url::Url};
use log::error;
use std::{collections::HashSet, sync::Arc, time::Duration};
use tokio::sync::RwLock;
@@ -32,8 +32,8 @@ impl<T> MaybeCached<T> {
#[derive(Clone)]
pub struct ActorCache {
db: Db,
cache: Arc<RwLock<TtlCache<XsdAnyUri, Actor>>>,
following: Arc<RwLock<HashSet<XsdAnyUri>>>,
cache: Arc<RwLock<TtlCache<Url, Actor>>>,
following: Arc<RwLock<HashSet<Url>>>,
}
impl ActorCache {
@@ -49,43 +49,25 @@ impl ActorCache {
cache
}
pub async fn is_following(&self, id: &XsdAnyUri) -> bool {
pub async fn is_following(&self, id: &Url) -> bool {
self.following.read().await.contains(id)
}
pub async fn get_no_cache(
&self,
id: &XsdAnyUri,
requests: &Requests,
) -> Result<Actor, MyError> {
pub async fn get_no_cache(&self, id: &Url, requests: &Requests) -> Result<Actor, MyError> {
let accepted_actor = requests.fetch::<AcceptedActors>(id.as_str()).await?;
let input_host = id.as_url().host();
let accepted_actor_id = accepted_actor.id().ok_or(MyError::MissingId)?;
let actor_host = accepted_actor_id.as_url().host();
let inbox_host = get_inbox(&accepted_actor).as_url().host();
let input_domain = id.domain().ok_or(MyError::MissingDomain)?;
let accepted_actor_id = accepted_actor
.id(&input_domain)?
.ok_or(MyError::MissingId)?;
if input_host != actor_host {
let input_host = input_host.map(|h| h.to_string()).unwrap_or_default();
let actor_host = actor_host.map(|h| h.to_string()).unwrap_or_default();
return Err(MyError::HostMismatch(input_host, actor_host));
}
if actor_host != inbox_host {
let actor_host = actor_host.map(|h| h.to_string()).unwrap_or_default();
let inbox_host = inbox_host.map(|h| h.to_string()).unwrap_or_default();
return Err(MyError::HostMismatch(actor_host, inbox_host));
}
let inbox = get_inbox(&accepted_actor).clone();
let inbox = get_inbox(&accepted_actor)?.clone();
let actor = Actor {
id: accepted_actor_id.clone(),
id: accepted_actor_id.clone().into(),
public_key: accepted_actor.ext_one.public_key.public_key_pem,
public_key_id: accepted_actor.ext_one.public_key.id,
inbox,
inbox: inbox.into(),
};
self.cache
@@ -99,11 +81,7 @@ impl ActorCache {
Ok(actor)
}
pub async fn get(
&self,
id: &XsdAnyUri,
requests: &Requests,
) -> Result<MaybeCached<Actor>, MyError> {
pub async fn get(&self, id: &Url, requests: &Requests) -> Result<MaybeCached<Actor>, MyError> {
if let Some(actor) = self.cache.read().await.get(id) {
return Ok(MaybeCached::Cached(actor.clone()));
}
@@ -125,11 +103,11 @@ impl ActorCache {
self.save(actor.clone()).await
}
pub async fn cache_follower(&self, id: XsdAnyUri) {
pub async fn cache_follower(&self, id: Url) {
self.following.write().await.insert(id);
}
pub async fn bust_follower(&self, id: &XsdAnyUri) {
pub async fn bust_follower(&self, id: &Url) {
self.following.write().await.remove(id);
}
@@ -174,7 +152,7 @@ impl ActorCache {
Ok(None)
}
async fn lookup(&self, id: &XsdAnyUri) -> Result<Option<Actor>, MyError> {
async fn lookup(&self, id: &Url) -> Result<Option<Actor>, MyError> {
let row_opt = self
.db
.pool()
@@ -203,10 +181,10 @@ impl ActorCache {
let public_key_id: String = row.try_get(2)?;
Ok(Some(Actor {
id: id.clone(),
inbox: uri!(inbox),
id: id.clone().into(),
inbox: uri!(inbox).into(),
public_key: row.try_get(1)?,
public_key_id: uri!(public_key_id),
public_key_id: uri!(public_key_id).into(),
}))
}
@@ -262,12 +240,7 @@ impl ActorCache {
Ok(())
}
async fn update(
&self,
id: &XsdAnyUri,
public_key: &str,
public_key_id: &XsdAnyUri,
) -> Result<(), MyError> {
async fn update(&self, id: &Url, public_key: &str, public_key_id: &Url) -> Result<(), MyError> {
self.db
.pool()
.get()
@@ -335,11 +308,11 @@ impl ActorCache {
}
}
fn get_inbox(actor: &AcceptedActors) -> &XsdAnyUri {
actor
.endpoints()
.and_then(|e| e.shared_inbox.as_ref())
.unwrap_or(actor.inbox())
fn get_inbox(actor: &AcceptedActors) -> Result<&Url, MyError> {
Ok(actor
.endpoints()?
.and_then(|e| e.shared_inbox)
.unwrap_or(actor.inbox()?))
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+7 -7
View File
@@ -1,5 +1,5 @@
use crate::{db::Db, error::MyError};
use activitystreams_new::primitives::XsdAnyUri;
use activitystreams_new::url::Url;
use async_mutex::Mutex;
use bytes::Bytes;
use futures::join;
@@ -14,8 +14,8 @@ static MEDIA_DURATION: Duration = Duration::from_secs(60 * 60 * 24 * 2);
#[derive(Clone)]
pub struct Media {
db: Db,
inverse: Arc<Mutex<HashMap<XsdAnyUri, Uuid>>>,
url_cache: Arc<Mutex<LruCache<Uuid, XsdAnyUri>>>,
inverse: Arc<Mutex<HashMap<Url, Uuid>>>,
url_cache: Arc<Mutex<LruCache<Uuid, Url>>>,
byte_cache: Arc<RwLock<TtlCache<Uuid, (String, Bytes)>>>,
}
@@ -29,7 +29,7 @@ impl Media {
}
}
pub async fn get_uuid(&self, url: &XsdAnyUri) -> Result<Option<Uuid>, MyError> {
pub async fn get_uuid(&self, url: &Url) -> Result<Option<Uuid>, MyError> {
let res = self.inverse.lock().await.get(url).cloned();
let uuid = match res {
Some(uuid) => uuid,
@@ -90,7 +90,7 @@ impl Media {
Ok(None)
}
pub async fn get_url(&self, uuid: Uuid) -> Result<Option<XsdAnyUri>, MyError> {
pub async fn get_url(&self, uuid: Uuid) -> Result<Option<Url>, MyError> {
if let Some(url) = self.url_cache.lock().await.get(&uuid).cloned() {
return Ok(Some(url));
}
@@ -111,7 +111,7 @@ impl Media {
if let Some(row) = row_opt {
let url: String = row.try_get(0)?;
let url: XsdAnyUri = url.parse()?;
let url: Url = url.parse()?;
return Ok(Some(url));
}
@@ -122,7 +122,7 @@ impl Media {
self.byte_cache.read().await.get(&uuid).cloned()
}
pub async fn store_url(&self, url: &XsdAnyUri) -> Result<Uuid, MyError> {
pub async fn store_url(&self, url: &Url) -> Result<Uuid, MyError> {
let uuid = Uuid::new_v4();
let (_, _, res) = join!(
+19 -20
View File
@@ -1,5 +1,5 @@
use crate::{db::Db, error::MyError};
use activitystreams_new::{primitives::XsdAnyUri, uri};
use activitystreams_new::{primitives::XsdAnyUri, uri, url::Url};
use log::{debug, error};
use std::{
collections::{HashMap, HashSet},
@@ -10,13 +10,13 @@ use tokio::sync::RwLock;
use tokio_postgres::types::Json;
use uuid::Uuid;
pub type ListenersCache = Arc<RwLock<HashSet<XsdAnyUri>>>;
pub type ListenersCache = Arc<RwLock<HashSet<Url>>>;
#[derive(Clone)]
pub struct NodeCache {
db: Db,
listeners: ListenersCache,
nodes: Arc<RwLock<HashMap<XsdAnyUri, Node>>>,
nodes: Arc<RwLock<HashMap<Url, Node>>>,
}
impl NodeCache {
@@ -45,7 +45,7 @@ impl NodeCache {
.collect()
}
pub async fn is_nodeinfo_outdated(&self, listener: &XsdAnyUri) -> bool {
pub async fn is_nodeinfo_outdated(&self, listener: &Url) -> bool {
let read_guard = self.nodes.read().await;
let node = match read_guard.get(listener) {
@@ -65,7 +65,7 @@ impl NodeCache {
}
}
pub async fn is_contact_outdated(&self, listener: &XsdAnyUri) -> bool {
pub async fn is_contact_outdated(&self, listener: &Url) -> bool {
let read_guard = self.nodes.read().await;
let node = match read_guard.get(listener) {
@@ -85,7 +85,7 @@ impl NodeCache {
}
}
pub async fn is_instance_outdated(&self, listener: &XsdAnyUri) -> bool {
pub async fn is_instance_outdated(&self, listener: &Url) -> bool {
let read_guard = self.nodes.read().await;
let node = match read_guard.get(listener) {
@@ -196,7 +196,7 @@ impl NodeCache {
pub async fn set_info(
&self,
listener: &XsdAnyUri,
listener: &Url,
software: String,
version: String,
reg: bool,
@@ -221,7 +221,7 @@ impl NodeCache {
pub async fn set_instance(
&self,
listener: &XsdAnyUri,
listener: &Url,
title: String,
description: String,
version: String,
@@ -248,11 +248,11 @@ impl NodeCache {
pub async fn set_contact(
&self,
listener: &XsdAnyUri,
listener: &Url,
username: String,
display_name: String,
url: XsdAnyUri,
avatar: XsdAnyUri,
url: Url,
avatar: Url,
) -> Result<(), MyError> {
if !self.listeners.read().await.contains(listener) {
let mut nodes = self.nodes.write().await;
@@ -272,7 +272,7 @@ impl NodeCache {
Ok(())
}
pub async fn save(&self, listener: &XsdAnyUri, node: &Node) -> Result<(), MyError> {
pub async fn save(&self, listener: &Url, node: &Node) -> Result<(), MyError> {
let row_opt = self
.db
.pool()
@@ -328,21 +328,20 @@ impl NodeCache {
#[derive(Clone, Debug)]
pub struct Node {
pub base: XsdAnyUri,
pub base: Url,
pub info: Option<Info>,
pub instance: Option<Instance>,
pub contact: Option<Contact>,
}
impl Node {
pub fn new(mut uri: XsdAnyUri) -> Self {
let url = uri.as_mut();
pub fn new(mut url: Url) -> Self {
url.set_fragment(None);
url.set_query(None);
url.set_path("");
Node {
base: uri,
base: url,
info: None,
instance: None,
contact: None,
@@ -382,14 +381,14 @@ impl Node {
&mut self,
username: String,
display_name: String,
url: XsdAnyUri,
avatar: XsdAnyUri,
url: Url,
avatar: Url,
) -> &mut Self {
self.contact = Some(Contact {
username,
display_name,
url,
avatar,
url: url.into(),
avatar: avatar.into(),
updated: SystemTime::now(),
});
self
+15 -15
View File
@@ -5,7 +5,7 @@ use crate::{
error::MyError,
requests::Requests,
};
use activitystreams_new::primitives::XsdAnyUri;
use activitystreams_new::url::Url;
use actix_rt::{
spawn,
time::{interval_at, Instant},
@@ -24,10 +24,10 @@ pub struct State {
pub public_key: RSAPublicKey,
private_key: RSAPrivateKey,
config: Config,
actor_id_cache: Arc<RwLock<LruCache<XsdAnyUri, XsdAnyUri>>>,
actor_id_cache: Arc<RwLock<LruCache<Url, Url>>>,
blocks: Arc<RwLock<HashSet<String>>>,
whitelists: Arc<RwLock<HashSet<String>>>,
listeners: Arc<RwLock<HashSet<XsdAnyUri>>>,
listeners: Arc<RwLock<HashSet<Url>>>,
node_cache: NodeCache,
}
@@ -57,11 +57,11 @@ impl State {
self.blocks.write().await.remove(block);
}
pub async fn bust_listener(&self, inbox: &XsdAnyUri) {
pub async fn bust_listener(&self, inbox: &Url) {
self.listeners.write().await.remove(inbox);
}
pub async fn listeners(&self) -> Vec<XsdAnyUri> {
pub async fn listeners(&self) -> Vec<Url> {
self.listeners.read().await.iter().cloned().collect()
}
@@ -69,13 +69,13 @@ impl State {
self.blocks.read().await.iter().cloned().collect()
}
pub async fn listeners_without(&self, inbox: &XsdAnyUri, domain: &str) -> Vec<XsdAnyUri> {
pub async fn listeners_without(&self, inbox: &Url, domain: &str) -> Vec<Url> {
self.listeners
.read()
.await
.iter()
.filter_map(|listener| {
if let Some(dom) = listener.as_url().domain() {
if let Some(dom) = listener.domain() {
if listener != inbox && dom != domain {
return Some(listener.clone());
}
@@ -86,35 +86,35 @@ impl State {
.collect()
}
pub async fn is_whitelisted(&self, actor_id: &XsdAnyUri) -> bool {
pub async fn is_whitelisted(&self, actor_id: &Url) -> bool {
if !self.config.whitelist_mode() {
return true;
}
if let Some(domain) = actor_id.as_url().domain() {
if let Some(domain) = actor_id.domain() {
return self.whitelists.read().await.contains(domain);
}
false
}
pub async fn is_blocked(&self, actor_id: &XsdAnyUri) -> bool {
if let Some(domain) = actor_id.as_url().domain() {
pub async fn is_blocked(&self, actor_id: &Url) -> bool {
if let Some(domain) = actor_id.domain() {
return self.blocks.read().await.contains(domain);
}
true
}
pub async fn is_listener(&self, actor_id: &XsdAnyUri) -> bool {
pub async fn is_listener(&self, actor_id: &Url) -> bool {
self.listeners.read().await.contains(actor_id)
}
pub async fn is_cached(&self, object_id: &XsdAnyUri) -> bool {
pub async fn is_cached(&self, object_id: &Url) -> bool {
self.actor_id_cache.read().await.contains(object_id)
}
pub async fn cache(&self, object_id: XsdAnyUri, actor_id: XsdAnyUri) {
pub async fn cache(&self, object_id: Url, actor_id: Url) {
self.actor_id_cache.write().await.put(object_id, actor_id);
}
@@ -126,7 +126,7 @@ impl State {
self.whitelists.write().await.insert(host);
}
pub async fn cache_listener(&self, listener: XsdAnyUri) {
pub async fn cache_listener(&self, listener: Url) {
self.listeners.write().await.insert(listener);
}
+4 -4
View File
@@ -1,5 +1,5 @@
use crate::error::MyError;
use activitystreams_new::primitives::XsdAnyUri;
use activitystreams_new::url::Url;
use deadpool_postgres::{Manager, Pool};
use log::{info, warn};
use rsa::RSAPrivateKey;
@@ -32,7 +32,7 @@ impl Db {
&self.pool
}
pub async fn remove_listener(&self, inbox: XsdAnyUri) -> Result<(), MyError> {
pub async fn remove_listener(&self, inbox: Url) -> Result<(), MyError> {
info!("DELETE FROM listeners WHERE actor_id = {};", inbox.as_str());
self.pool
.get()
@@ -46,7 +46,7 @@ impl Db {
Ok(())
}
pub async fn add_listener(&self, inbox: XsdAnyUri) -> Result<(), MyError> {
pub async fn add_listener(&self, inbox: Url) -> Result<(), MyError> {
info!(
"INSERT INTO listeners (actor_id, created_at) VALUES ($1::TEXT, 'now'); [{}]",
inbox.as_str(),
@@ -129,7 +129,7 @@ impl Db {
parse_rows(rows)
}
pub async fn hydrate_listeners(&self) -> Result<HashSet<XsdAnyUri>, MyError> {
pub async fn hydrate_listeners(&self) -> Result<HashSet<Url>, MyError> {
info!("SELECT actor_id FROM listeners");
let rows = self
.pool
+7 -4
View File
@@ -1,4 +1,4 @@
use activitystreams_new::primitives::XsdAnyUriError;
use activitystreams_new::{error::DomainError, url::ParseError};
use actix_web::{
error::{BlockingError, ResponseError},
http::StatusCode,
@@ -25,7 +25,7 @@ pub enum MyError {
Key(#[from] KeyError),
#[error("Couldn't parse URI, {0}")]
Uri(#[from] XsdAnyUriError),
Uri(#[from] ParseError),
#[error("Couldn't perform IO, {0}")]
Io(#[from] Error),
@@ -69,8 +69,8 @@ pub enum MyError {
#[error("Too many CPUs, {0}")]
CpuCount(#[from] std::num::TryFromIntError),
#[error("Hosts don't match, {0}, {1}")]
HostMismatch(String, String),
#[error("{0}")]
HostMismatch(#[from] DomainError),
#[error("Invalid or missing content type")]
ContentType,
@@ -108,6 +108,9 @@ pub enum MyError {
#[error("Input is missing a 'id' field")]
MissingId,
#[error("Url is missing a domain")]
MissingDomain,
#[error("URI is missing domain field")]
Domain,
+12 -6
View File
@@ -7,7 +7,7 @@ use crate::{
DeliverMany, JobState,
},
};
use activitystreams_new::{activity::Announce as AsAnnounce, primitives::XsdAnyUri};
use activitystreams_new::{activity::Announce as AsAnnounce, primitives::XsdAnyUri, url::Url};
use background_jobs::ActixJob;
use std::{future::Future, pin::Pin};
@@ -18,8 +18,11 @@ pub struct Announce {
}
impl Announce {
pub fn new(object_id: XsdAnyUri, actor: Actor) -> Self {
Announce { object_id, actor }
pub fn new(object_id: Url, actor: Actor) -> Self {
Announce {
object_id: object_id.into(),
actor,
}
}
async fn perform(self, state: JobState) -> Result<(), anyhow::Error> {
@@ -31,7 +34,10 @@ impl Announce {
.job_server
.queue(DeliverMany::new(inboxes, announce)?)?;
state.state.cache(self.object_id, activity_id).await;
state
.state
.cache(self.object_id.into_inner(), activity_id)
.await;
Ok(())
}
}
@@ -39,8 +45,8 @@ impl Announce {
// Generate a type that says "Look at this object"
fn generate_announce(
config: &Config,
activity_id: &XsdAnyUri,
object_id: &XsdAnyUri,
activity_id: &Url,
object_id: &Url,
) -> Result<AsAnnounce, MyError> {
let announce = AsAnnounce::new(config.generate_url(UrlKind::Actor), object_id.clone());
+10 -11
View File
@@ -8,7 +8,7 @@ use crate::{
use activitystreams_new::{
activity::{Accept as AsAccept, Follow as AsFollow},
prelude::*,
primitives::XsdAnyUri,
url::Url,
};
use background_jobs::ActixJob;
use std::{future::Future, pin::Pin};
@@ -31,7 +31,10 @@ impl Follow {
async fn perform(self, state: JobState) -> Result<(), anyhow::Error> {
if !self.is_listener {
state.db.add_listener(self.actor.inbox.clone()).await?;
state
.db
.add_listener(self.actor.inbox.clone().into_inner())
.await?;
}
let my_id = state.config.generate_url(UrlKind::Actor);
@@ -48,7 +51,7 @@ impl Follow {
let accept = generate_accept_follow(
&state.config,
&self.actor.id,
self.input.id().ok_or(MyError::MissingId)?,
self.input.id_unchecked().ok_or(MyError::MissingId)?,
&my_id,
)?;
@@ -60,11 +63,7 @@ impl Follow {
}
// Generate a type that says "I want to follow you"
fn generate_follow(
config: &Config,
actor_id: &XsdAnyUri,
my_id: &XsdAnyUri,
) -> Result<AsFollow, MyError> {
fn generate_follow(config: &Config, actor_id: &Url, my_id: &Url) -> Result<AsFollow, MyError> {
let follow = AsFollow::new(my_id.clone(), actor_id.clone());
prepare_activity(
@@ -77,9 +76,9 @@ fn generate_follow(
// Generate a type that says "I accept your follow request"
fn generate_accept_follow(
config: &Config,
actor_id: &XsdAnyUri,
input_id: &XsdAnyUri,
my_id: &XsdAnyUri,
actor_id: &Url,
input_id: &Url,
my_id: &Url,
) -> Result<AsAccept, MyError> {
let mut follow = AsFollow::new(actor_id.clone(), my_id.clone());
+6 -18
View File
@@ -7,8 +7,8 @@ use activitystreams_new::{
activity::{Follow as AsFollow, Undo as AsUndo},
context,
prelude::*,
primitives::XsdAnyUri,
security,
url::Url,
};
use std::convert::TryInto;
@@ -20,24 +20,16 @@ mod undo;
pub use self::{announce::Announce, follow::Follow, forward::Forward, reject::Reject, undo::Undo};
async fn get_inboxes(
state: &State,
actor: &Actor,
object_id: &XsdAnyUri,
) -> Result<Vec<XsdAnyUri>, MyError> {
let domain = object_id
.as_url()
.host()
.ok_or(MyError::Domain)?
.to_string();
async fn get_inboxes(state: &State, actor: &Actor, object_id: &Url) -> Result<Vec<Url>, MyError> {
let domain = object_id.host().ok_or(MyError::Domain)?.to_string();
Ok(state.listeners_without(&actor.inbox, &domain).await)
}
fn prepare_activity<T, U, V, Kind>(
mut t: T,
id: impl TryInto<XsdAnyUri, Error = U>,
to: impl TryInto<XsdAnyUri, Error = V>,
id: impl TryInto<Url, Error = U>,
to: impl TryInto<Url, Error = V>,
) -> Result<T, MyError>
where
T: ObjectExt<Kind> + BaseExt<Kind>,
@@ -50,11 +42,7 @@ where
}
// Generate a type that says "I want to stop following you"
fn generate_undo_follow(
config: &Config,
actor_id: &XsdAnyUri,
my_id: &XsdAnyUri,
) -> Result<AsUndo, MyError> {
fn generate_undo_follow(config: &Config, actor_id: &Url, my_id: &Url) -> Result<AsUndo, MyError> {
let mut follow = AsFollow::new(my_id.clone(), actor_id.clone());
follow.set_id(config.generate_url(UrlKind::Activity));
+4 -1
View File
@@ -12,7 +12,10 @@ pub struct Reject(pub Actor);
impl Reject {
async fn perform(self, state: JobState) -> Result<(), anyhow::Error> {
if state.actors.unfollower(&self.0).await?.is_some() {
state.db.remove_listener(self.0.inbox.clone()).await?;
state
.db
.remove_listener(self.0.inbox.clone().into_inner())
.await?;
}
let my_id = state.config.generate_url(UrlKind::Actor);
+4 -1
View File
@@ -22,7 +22,10 @@ impl Undo {
let was_following = state.actors.is_following(&self.actor.id).await;
if state.actors.unfollower(&self.actor).await?.is_some() {
state.db.remove_listener(self.actor.inbox.clone()).await?;
state
.db
.remove_listener(self.actor.inbox.clone().into_inner())
.await?;
}
if was_following {
+4 -1
View File
@@ -31,7 +31,10 @@ impl ActixJob for Deliver {
fn run(self, state: Self::State) -> Self::Future {
Box::pin(async move {
state.requests.deliver(self.to, &self.data).await?;
state
.requests
.deliver(self.to.into_inner(), &self.data)
.await?;
Ok(())
})
+3 -3
View File
@@ -2,7 +2,7 @@ use crate::{
error::MyError,
jobs::{Deliver, JobState},
};
use activitystreams_new::primitives::XsdAnyUri;
use activitystreams_new::{primitives::XsdAnyUri, url::Url};
use anyhow::Error;
use background_jobs::ActixJob;
use futures::future::{ready, Ready};
@@ -14,12 +14,12 @@ pub struct DeliverMany {
}
impl DeliverMany {
pub fn new<T>(to: Vec<XsdAnyUri>, data: T) -> Result<Self, MyError>
pub fn new<T>(to: Vec<Url>, data: T) -> Result<Self, MyError>
where
T: serde::ser::Serialize,
{
Ok(DeliverMany {
to,
to: to.into_iter().map(XsdAnyUri::from).collect(),
data: serde_json::to_value(data)?,
})
}
+16 -17
View File
@@ -2,7 +2,7 @@ use crate::{
config::UrlKind,
jobs::{cache_media::CacheMedia, JobState},
};
use activitystreams_new::primitives::XsdAnyUri;
use activitystreams_new::{primitives::XsdAnyUri, url::Url};
use anyhow::Error;
use background_jobs::ActixJob;
use futures::join;
@@ -14,26 +14,25 @@ pub struct QueryInstance {
}
impl QueryInstance {
pub fn new(listener: XsdAnyUri) -> Self {
QueryInstance { listener }
pub fn new(listener: Url) -> Self {
QueryInstance {
listener: listener.into(),
}
}
async fn perform(mut self, state: JobState) -> Result<(), Error> {
let listener = self.listener.clone();
let (o1, o2) = join!(
state.node_cache.is_contact_outdated(&listener),
state.node_cache.is_instance_outdated(&listener),
state.node_cache.is_contact_outdated(&self.listener),
state.node_cache.is_instance_outdated(&self.listener),
);
if !(o1 || o2) {
return Ok(());
}
let url = self.listener.as_url_mut();
url.set_fragment(None);
url.set_query(None);
url.set_path("api/v1/instance");
self.listener.set_fragment(None);
self.listener.set_query(None);
self.listener.set_path("api/v1/instance");
let instance = state
.requests
@@ -48,11 +47,11 @@ impl QueryInstance {
if let Some(mut contact) = instance.contact {
let uuid = if let Some(uuid) = state.media.get_uuid(&contact.avatar).await? {
contact.avatar = state.config.generate_url(UrlKind::Media(uuid));
contact.avatar = state.config.generate_url(UrlKind::Media(uuid)).into();
uuid
} else {
let uuid = state.media.store_url(&contact.avatar).await?;
contact.avatar = state.config.generate_url(UrlKind::Media(uuid));
contact.avatar = state.config.generate_url(UrlKind::Media(uuid)).into();
uuid
};
@@ -61,11 +60,11 @@ impl QueryInstance {
state
.node_cache
.set_contact(
&listener,
&self.listener,
contact.username,
contact.display_name,
contact.url,
contact.avatar,
contact.url.into_inner(),
contact.avatar.into_inner(),
)
.await?;
}
@@ -75,7 +74,7 @@ impl QueryInstance {
state
.node_cache
.set_instance(
&listener,
&self.listener,
instance.title,
description,
instance.version,
+10 -11
View File
@@ -1,5 +1,5 @@
use crate::jobs::JobState;
use activitystreams_new::primitives::XsdAnyUri;
use activitystreams_new::{primitives::XsdAnyUri, url::Url};
use anyhow::Error;
use background_jobs::ActixJob;
use std::{future::Future, pin::Pin};
@@ -10,21 +10,20 @@ pub struct QueryNodeinfo {
}
impl QueryNodeinfo {
pub fn new(listener: XsdAnyUri) -> Self {
QueryNodeinfo { listener }
pub fn new(listener: Url) -> Self {
QueryNodeinfo {
listener: listener.into(),
}
}
async fn perform(mut self, state: JobState) -> Result<(), Error> {
let listener = self.listener.clone();
if !state.node_cache.is_nodeinfo_outdated(&listener).await {
if !state.node_cache.is_nodeinfo_outdated(&self.listener).await {
return Ok(());
}
let url = self.listener.as_url_mut();
url.set_fragment(None);
url.set_query(None);
url.set_path(".well-known/nodeinfo");
self.listener.set_fragment(None);
self.listener.set_query(None);
self.listener.set_path(".well-known/nodeinfo");
let well_known = state
.requests
@@ -42,7 +41,7 @@ impl QueryNodeinfo {
state
.node_cache
.set_info(
&listener,
&self.listener,
nodeinfo.software.name,
nodeinfo.software.version,
nodeinfo.open_registrations,
+1 -1
View File
@@ -20,7 +20,7 @@ impl MyVerify {
signing_string: String,
) -> Result<bool, MyError> {
let mut uri = uri!(key_id);
uri.as_url_mut().set_fragment(None);
uri.set_fragment(None);
let actor = self.1.get(&uri, &self.0).await?;
let was_cached = actor.is_cached();
let actor = actor.into_inner();
+5 -5
View File
@@ -3,7 +3,7 @@ use crate::{
db::listen,
jobs::{JobServer, QueryInstance, QueryNodeinfo},
};
use activitystreams_new::primitives::XsdAnyUri;
use activitystreams_new::url::Url;
use actix_rt::{spawn, time::delay_for};
use futures::stream::{poll_fn, StreamExt};
use log::{debug, error, warn};
@@ -144,7 +144,7 @@ impl Listener for NewListeners {
}
fn execute(&self, payload: &str) {
if let Ok(uri) = payload.parse::<XsdAnyUri>() {
if let Ok(uri) = payload.parse::<Url>() {
debug!("Caching listener {}", uri);
let state = self.0.clone();
let _ = self.1.queue(QueryInstance::new(uri.clone()));
@@ -162,7 +162,7 @@ impl Listener for NewActors {
}
fn execute(&self, payload: &str) {
if let Ok(uri) = payload.parse::<XsdAnyUri>() {
if let Ok(uri) = payload.parse::<Url>() {
debug!("Caching actor {}", uri);
let actors = self.0.clone();
spawn(async move { actors.cache_follower(uri).await });
@@ -220,7 +220,7 @@ impl Listener for RmListeners {
}
fn execute(&self, payload: &str) {
if let Ok(uri) = payload.parse::<XsdAnyUri>() {
if let Ok(uri) = payload.parse::<Url>() {
debug!("Busting listener cache for {}", uri);
let state = self.0.clone();
spawn(async move { state.bust_listener(&uri).await });
@@ -236,7 +236,7 @@ impl Listener for RmActors {
}
fn execute(&self, payload: &str) {
if let Ok(uri) = payload.parse::<XsdAnyUri>() {
if let Ok(uri) = payload.parse::<Url>() {
debug!("Busting actor cache for {}", uri);
let actors = self.0.clone();
spawn(async move { actors.bust_follower(&uri).await });
+2 -2
View File
@@ -1,5 +1,5 @@
use crate::error::MyError;
use activitystreams_new::primitives::XsdAnyUri;
use activitystreams_new::url::Url;
use actix_web::{client::Client, http::header::Date};
use bytes::Bytes;
use http_signature_normalization_actix::prelude::*;
@@ -159,7 +159,7 @@ impl Requests {
Ok((content_type, bytes))
}
pub async fn deliver<T>(&self, inbox: XsdAnyUri, item: &T) -> Result<(), MyError>
pub async fn deliver<T>(&self, inbox: Url, item: &T) -> Result<(), MyError>
where
T: serde::ser::Serialize,
{
+2 -2
View File
@@ -23,8 +23,8 @@ pub async fn route(
ApActor::new(config.generate_url(UrlKind::Inbox), Application::new()),
PublicKey {
public_key: PublicKeyInner {
id: config.generate_url(UrlKind::MainKey),
owner: config.generate_url(UrlKind::Actor),
id: config.generate_url(UrlKind::MainKey).into(),
owner: config.generate_url(UrlKind::Actor).into(),
public_key_pem: state.public_key.to_pem_pkcs8()?,
},
},
+7 -11
View File
@@ -9,11 +9,7 @@ use crate::{
routes::accepted,
};
use activitystreams_new::{
activity,
base::AnyBase,
prelude::*,
primitives::{OneOrMany, XsdAnyUri},
public,
activity, base::AnyBase, prelude::*, primitives::OneOrMany, public, url::Url,
};
use actix_web::{web, HttpResponse};
use futures::join;
@@ -33,7 +29,7 @@ pub async fn route(
let actor = actors
.get(
input.actor().as_single_id().ok_or(MyError::MissingId)?,
input.actor()?.as_single_id().ok_or(MyError::MissingId)?,
&client,
)
.await?
@@ -97,7 +93,7 @@ fn kind_str(base: &AnyBase) -> Result<&str, MyError> {
base.kind_str().ok_or(MyError::MissingKind)
}
fn id_string(id: Option<&XsdAnyUri>) -> Result<String, MyError> {
fn id_string(id: Option<&Url>) -> Result<String, MyError> {
id.map(|s| s.to_string()).ok_or(MyError::MissingId)
}
@@ -117,7 +113,7 @@ async fn handle_accept(config: &Config, input: AcceptedActivities) -> Result<(),
if !follow.actor_is(&config.generate_url(UrlKind::Actor)) {
return Err(MyError::WrongActor(id_string(
follow.actor().as_single_id(),
follow.actor()?.as_single_id(),
)?));
}
@@ -141,7 +137,7 @@ async fn handle_reject(
if !follow.actor_is(&config.generate_url(UrlKind::Actor)) {
return Err(MyError::WrongActor(id_string(
follow.actor().as_single_id(),
follow.actor()?.as_single_id(),
)?));
}
@@ -170,7 +166,7 @@ async fn handle_undo(
}
}
let my_id: XsdAnyUri = config.generate_url(UrlKind::Actor);
let my_id: Url = config.generate_url(UrlKind::Actor);
if !undone_object.object_is(&my_id) && !undone_object.object_is(&public()) {
return Err(MyError::WrongActor(id_string(
@@ -220,7 +216,7 @@ async fn handle_follow(
actor: Actor,
is_listener: bool,
) -> Result<(), MyError> {
let my_id: XsdAnyUri = config.generate_url(UrlKind::Actor);
let my_id: Url = config.generate_url(UrlKind::Actor);
if !input.object_is(&my_id) && !input.object_is(&public()) {
return Err(MyError::WrongActor(id_string(
+1 -1
View File
@@ -49,7 +49,7 @@ pub async fn route(config: web::Data<Config>, state: web::Data<State>) -> web::J
.listeners()
.await
.iter()
.filter_map(|listener| listener.as_url().domain())
.filter_map(|listener| listener.domain())
.map(|s| s.to_owned())
.collect(),
blocks: if config.publish_blocks() {