1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
//! Saves ActivityPub objects into the database or sends them to remote servers.

use crate::activitypub::{Object, ObjectOrLink, ObjectsOrLinks};
use crate::database::Database;
use crate::remote::{RemoteAccessError, RemoteAccessor};
use std::collections::HashSet;

#[allow(unused_imports)]
use crate::http_api;
/// Adds the activity to the database, and applies any side effects it has.
/// Called from both [`http_api::users::post_inbox`] and
/// [`http_api::users::post_outbox`].
pub async fn receive(
    mut activity: Object<'_>,
    db: &Database,
    remote: &RemoteAccessor,
    local: bool,
) -> Result<(), ActivityBrokeringError> {
    // Check if this activity has already been received
    if db.get_object(activity.id.as_ref().unwrap(), None).await?.is_some() {
        return Ok(());
    }

    let bto = activity.bto.take();
    let bcc = activity.bcc.take();

    // Update database based on the activity type (e.g. save the object into the db as well)
    if activity.has_type("Create") {
        let Some(object) = activity.object.clone() else {
            return Err(ActivityBrokeringError::MissingObject);
        };
        let mut object = deref_obj(object, db, remote).await?;
        object.compact();
        db.insert(&object).await?;
        activity.object = Some(ObjectOrLink::Object(Box::new(object)));
    } else {
        return Err(ActivityBrokeringError::UnrecognizedType);
    }

    // Compact the activity for storage, but save the object/target for inbox
    // delivery.
    let Some(actor) = activity.actor.clone() else {
        return Err(ActivityBrokeringError::MissingActor);
    };
    let mut actor = deref_objs([actor].into_iter(), db, remote).await?;
    let object = replace_obj_with_link(&mut activity.object);
    let target = replace_obj_with_link(&mut activity.target);
    activity.compact();
    db.insert(&activity).await?;

    // Save the relevant dereferenced objects to db
    for actor_obj in &actor {
        db.insert(actor_obj).await?;
    }

    // Restore compacted properties
    if let Some(object) = object {
        activity.object = Some(ObjectOrLink::Object(Box::new(object)));
    }
    if let Some(target) = target {
        activity.target = Some(ObjectOrLink::Object(Box::new(target)));
    }
    if actor.len() == 1 {
        activity.actor = Some(ObjectsOrLinks::Single(ObjectOrLink::Object(Box::new(actor.remove(0)))));
    } else {
        let actor = actor
            .into_iter()
            .map(|obj| ObjectOrLink::Object(Box::new(obj)))
            .collect::<Vec<_>>();
        activity.actor = Some(ObjectsOrLinks::Multiple(actor));
    }

    // Inbox delivery
    // TODO: Delivery to collections (e.g. followers)
    // TODO: Forward from inbox
    // (Deliver non-local activities if they're sent to a collection on this
    // server and have an object/target/tag/inReplyTo owned by this server.)
    if local {
        deliver_to_inboxes(&activity, bto, bcc, db, remote).await?;
    }

    Ok(())
}

#[allow(unused_imports)]
use crate::activitypub::inbox_queue;
/// Dereferences the inboxes and queues up deliveries of the given activity to
/// them for [`inbox_queue`].
async fn deliver_to_inboxes(
    activity: &Object<'_>,
    bto: Option<ObjectsOrLinks<'_>>,
    bcc: Option<ObjectsOrLinks<'_>>,
    db: &Database,
    remote: &RemoteAccessor,
) -> Result<(), ActivityBrokeringError> {
    let inboxes = (bto.into_iter())
        .chain(bcc.into_iter())
        .chain(activity.to.clone().into_iter())
        .chain(activity.cc.clone().into_iter())
        .chain(activity.audience.clone().into_iter());
    let inboxes = deref_objs(inboxes, db, remote)
        .await
        .map_err(ActivityBrokeringError::InboxActorDeref)?
        .into_iter()
        .filter(|actor| {
            // Don't send the activity back to the sender (activity.actor)
            if let (Some(actor_id), Some(activity_actor)) = (&actor.id, &activity.actor) {
                !activity_actor.has_id(actor_id)
            } else {
                false
            }
        })
        .map(|actor| {
            // Ensure the actors are actors and that they have inboxes, then collect the inboxes
            if !actor.is_actor() {
                return Err(ActivityBrokeringError::NonActorAddress(actor.id.unwrap().to_string()));
            }
            let Some(inbox) = actor.inbox else {
                return Err(ActivityBrokeringError::MissingInbox(actor.id.unwrap().to_string()));
            };
            Ok(inbox)
        })
        .collect::<Result<HashSet<_>, _>>()?;
    for inbox in inboxes {
        let activity_id = activity.id.as_ref().unwrap();
        if let Err(err) = db.deliver(&inbox, activity_id).await {
            tracing::warn!("Failed to schedule activity {activity_id} delivery to inbox {inbox}: {err}");
        }
    }
    Ok(())
}

/// Represents an issue with the values in an Activity during the receive or
/// delivery of it.
#[derive(Debug, thiserror::Error)]
pub enum ActivityBrokeringError {
    #[error("activity requires an object, but it is missing")]
    MissingObject,
    #[error("activity requires an actor, but it is missing")]
    MissingActor,
    #[error("unrecognized activity type")]
    UnrecognizedType,
    #[error("failed to dereference an object referred to in this activity")]
    Deref(#[from] DerefError),
    #[error("error saving activitypub object to the database")]
    Database(#[from] sqlx::Error),
    #[error("tried to deliver to a non-actor: {0}")]
    NonActorAddress(String),
    #[error("actor does not have an inbox: {0}")]
    MissingInbox(String),
    #[error("failed to dereference a recipient actor")]
    InboxActorDeref(DerefError),
}

/// If obj_or_link is an Object, returns it and leaves a Link in its place.
fn replace_obj_with_link<'a>(obj_or_link: &mut Option<ObjectOrLink<'a>>) -> Option<Object<'a>> {
    match obj_or_link.clone()? {
        ObjectOrLink::Object(obj) => {
            let link = obj.id.as_ref().unwrap().to_string();
            *obj_or_link = Some(ObjectOrLink::Link(link.into()));
            Some(*obj)
        }
        ObjectOrLink::Link(_) => None,
    }
}

/// If the given [`ObjectOrLink`] is an object, returns that, otherwise attempts
/// to fetch the object from the database, falling back to fetching it from its
/// origin server, and returns that.
async fn deref_obj<'a>(
    obj_or_link: ObjectOrLink<'a>,
    db: &'a Database,
    remote: &'a RemoteAccessor,
) -> Result<Object<'a>, DerefError> {
    match obj_or_link {
        ObjectOrLink::Object(obj) => Ok(*obj),
        ObjectOrLink::Link(link) => {
            if let Some(obj) = db.get_object(link.as_ref(), None).await? {
                Ok(obj)
            } else {
                let obj = remote.dereference_ap_object(link.as_ref()).await?;
                if let Some(mut obj) = obj {
                    obj.compact();
                    if let Err(err) = db.insert(&obj).await {
                        tracing::warn!("Failed to insert remote object that was just dereferenced: {err}");
                    }
                    Ok(obj)
                } else {
                    Err(DerefError::Missing)
                }
            }
        }
    }
}

/// Recursively dereferences objects included in each of the [`ObjectsOrLinks`]
/// using [`deref_obj`].
async fn deref_objs<'a>(
    objs: impl Iterator<Item = ObjectsOrLinks<'a>>,
    db: &'a Database,
    remote: &'a RemoteAccessor,
) -> Result<Vec<Object<'a>>, DerefError> {
    let (lower, upper) = objs.size_hint();
    let cap = upper.unwrap_or(lower);
    let mut dereferenced: Vec<Object> = Vec::with_capacity(cap);
    for obj in objs {
        match obj {
            ObjectsOrLinks::Single(obj_or_link) => dereferenced.push(deref_obj(obj_or_link, db, remote).await?),
            ObjectsOrLinks::Multiple(objs_or_links) => {
                for obj_or_link in objs_or_links {
                    // TODO: Deref all links in one query instead of one at a time
                    // (also take note of ones that couldn't be found in db, they have to be dereffed over remote)
                    dereferenced.push(deref_obj(obj_or_link, db, remote).await?);
                }
            }
        }
    }
    Ok(dereferenced)
}

/// Represents an issue while attempting to dereference an object
/// ([`deref_obj`]).
#[derive(Debug, thiserror::Error)]
pub enum DerefError {
    #[error("error dereferencing an object from the database")]
    Database(#[from] sqlx::Error),
    #[error("error fetching remote activitypub object")]
    Remote(#[from] RemoteAccessError),
    #[error("object does not exist (missing authorization?)")]
    Missing,
}