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
use crate::activitypub::activity_broker::ActivityBrokeringError;
use crate::activitypub::{activity_broker, Date, Object, ObjectOrLink};
use crate::http_api::{activity_id, activity_json, actor_id, get_ap_object, note_id, CanonicalServerUrl};
use crate::remote::RemoteAccessor;
use crate::{activitypub, Database};
use actix_web::{post, web, HttpResponse, Scope};
use once_cell::sync::Lazy;
use regex::Regex;
use time::OffsetDateTime;
pub fn service() -> Scope {
let accept_ap = activity_json::accept_guard;
web::scope("/u")
.service(post_inbox)
.service(post_outbox)
.service(register)
.route("/{user}", web::get().guard(accept_ap).to(get_ap_object))
.route("/{user}/inbox.json", web::get().guard(accept_ap).to(get_ap_object))
.route("/{user}/outbox.json", web::get().guard(accept_ap).to(get_ap_object))
.route("/{user}/activities/{id}", web::get().guard(accept_ap).to(get_ap_object))
.route("/{user}/notes/{id}", web::get().guard(accept_ap).to(get_ap_object))
}
#[post("/{username}")]
async fn register(
path: web::Path<String>,
db: web::Data<&'static Database>,
server_url: web::Data<CanonicalServerUrl>,
) -> HttpResponse {
tracing::debug!("Registering new user \"{path}\"");
static USERNAME_VALIDATOR: Lazy<Regex> = Lazy::new(|| Regex::new(r#"[A-Za-z0-9_]+"#).unwrap());
let username = path.as_str();
if !USERNAME_VALIDATOR.is_match(username) {
return HttpResponse::BadRequest().body("Username should only contain A-Z, a-z, 0-9, and underscores.");
}
let id = actor_id(&server_url, username);
let inbox = format!("{id}/inbox.json");
let outbox = format!("{id}/outbox.json");
let create_actor = || async {
let make_collection = |id: String| Object {
context: activitypub::activitystreams_context(),
type_: activitypub::type_ordered_collection(),
id: Some(id.into()),
..Default::default()
};
let inbox_collection = make_collection(inbox.clone());
let outbox_collection = make_collection(outbox.clone());
let actor = Object {
context: activitypub::activitystreams_context(),
type_: activitypub::type_person(),
id: Some(id.as_str().into()),
inbox: Some(inbox.into()),
outbox: Some(outbox.into()),
preferred_username: Some(username.into()),
name: Some(username.into()),
summary: Some("".into()),
..Default::default()
};
db.insert(&inbox_collection).await?;
db.insert(&outbox_collection).await?;
db.insert(&actor).await?;
Ok::<(), sqlx::Error>(())
};
match create_actor().await {
Ok(_) => HttpResponse::Created().insert_header(("Location", id)).finish(),
Err(err) => {
if let Ok(Some(existing_user)) = db.get_object(&id, None).await {
HttpResponse::Created()
.insert_header(("Location", existing_user.id.unwrap().as_ref()))
.finish()
} else {
tracing::warn!("Failed to insert new actor to db: {err}");
HttpResponse::ServiceUnavailable().finish()
}
}
}
}
#[post("/{username}/inbox.json", guard = "activity_json::content_type_guard")]
async fn post_inbox<'a>(
username: web::Path<String>,
activity: web::Json<activitypub::Object<'a>>,
db: web::Data<&'static Database>,
server_url: web::Data<CanonicalServerUrl>,
remote: web::Data<RemoteAccessor>,
) -> HttpResponse {
let actor_id = actor_id(&server_url, &username);
let inbox_id = format!("{actor_id}/inbox.json");
tracing::debug!("Post to inbox {inbox_id} received");
let Some(activity_id) = activity.0.id.clone() else {
return HttpResponse::BadRequest().body("Activity is missing the id");
};
match activity_broker::receive(activity.0, &db, &remote, false).await {
Ok(_) => match db.insert_to_collection(&inbox_id, &activity_id).await {
Ok(_) => HttpResponse::Ok().finish(),
Err(err) => {
tracing::warn!("Failed to insert activity {activity_id} to inbox {inbox_id}: {err}");
HttpResponse::ServiceUnavailable().finish()
}
},
Err(ActivityBrokeringError::Database(err)) => {
tracing::warn!("Failed to receive activity because of a database error: {err}");
HttpResponse::ServiceUnavailable().finish()
}
Err(err) => HttpResponse::BadRequest().body(format!("{err}")),
}
}
#[post("/{username}/outbox.json", guard = "activity_json::content_type_guard")]
async fn post_outbox<'a>(
username: web::Path<String>,
post: web::Json<activitypub::Object<'a>>,
db: web::Data<&'static Database>,
remote: web::Data<RemoteAccessor>,
server_url: web::Data<CanonicalServerUrl>,
) -> HttpResponse {
let mut note = post.0;
if note.has_type("Note") {
let actor_id = actor_id(&server_url, &username);
let activity_id = activity_id(&actor_id);
let note_id = note_id(&actor_id);
note.id = Some((¬e_id).into());
let Ok(Some(actor)) = db.get_object(&actor_id, None).await else {
return HttpResponse::NotFound().body("This outbox does not exist.");
};
let outbox = actor.outbox.as_ref().unwrap();
tracing::debug!("Post to outbox {outbox} received");
let ok_response = HttpResponse::Created()
.insert_header(("Location", activity_id.as_str()))
.finish();
let activity = activitypub::Object {
context: activitypub::activitystreams_context(),
type_: activitypub::type_create(),
id: Some((&activity_id).into()),
actor: Some(activitypub::ObjectsOrLinks::link((&actor_id).into())),
to: note.to.clone(),
cc: note.cc.clone(),
audience: note.audience.clone(),
bto: note.bto.take(),
bcc: note.bcc.take(),
published: Some(Date(OffsetDateTime::now_utc())),
object: Some(ObjectOrLink::Object(Box::new(note))),
..Default::default()
};
match activity_broker::receive(activity, db.as_ref(), remote.as_ref(), true).await {
Ok(_) => match db.insert_to_collection(outbox, &activity_id).await {
Ok(_) => ok_response,
Err(err) => {
tracing::error!("Failed to insert Note to outbox: {err}");
HttpResponse::ServiceUnavailable().finish()
}
},
Err(err @ ActivityBrokeringError::InboxActorDeref(_))
| Err(err @ ActivityBrokeringError::UnrecognizedType)
| Err(err @ ActivityBrokeringError::Deref(_))
| Err(err @ ActivityBrokeringError::MissingInbox(_))
| Err(err @ ActivityBrokeringError::MissingObject)
| Err(err @ ActivityBrokeringError::MissingActor)
| Err(err @ ActivityBrokeringError::NonActorAddress(_)) => {
HttpResponse::BadRequest().body(format!("{err}"))
}
Err(err) => {
tracing::error!("Failed to receive Note posted to outbox: {err}");
HttpResponse::ServiceUnavailable().finish()
}
}
} else {
HttpResponse::BadRequest().body("Not a Note.")
}
}