Plume/src/routes/instance.rs

288 lines
8.7 KiB
Rust
Raw Normal View History

2019-03-20 17:56:17 +01:00
use rocket::{
request::LenientForm,
response::{status, Redirect},
};
use rocket_contrib::json::Json;
use rocket_i18n::I18n;
use serde_json;
use validator::{Validate, ValidationErrors};
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
use inbox;
use plume_models::{
2019-03-20 17:56:17 +01:00
admin::Admin, comments::Comment, db_conn::DbConn, headers::Headers, instance::*, posts::Post,
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
safe_string::SafeString, users::User, Error, PlumeRocket, CONFIG,
2018-05-19 09:39:59 +02:00
};
use routes::{errors::ErrorPage, rocket_uri_macro_static_files, Page};
use template_utils::Ructe;
use Searcher;
2018-09-05 19:03:02 +02:00
#[get("/")]
pub fn index(conn: DbConn, user: Option<User>, intl: I18n) -> Result<Ructe, ErrorPage> {
let inst = Instance::get_local(&*conn)?;
let federated = Post::get_recents_page(&*conn, Page::default().limits())?;
let local = Post::get_instance_page(&*conn, inst.id, Page::default().limits())?;
let user_feed = user.clone().and_then(|user| {
let followed = user.get_followed(&*conn).ok()?;
let mut in_feed = followed.into_iter().map(|u| u.id).collect::<Vec<i32>>();
in_feed.push(user.id);
Post::user_feed_page(&*conn, in_feed, Page::default().limits()).ok()
});
Ok(render!(instance::index(
&(&*conn, &intl.catalog, user),
inst,
User::count_local(&*conn)?,
Post::count_local(&*conn)?,
local,
federated,
user_feed
)))
2018-04-29 19:50:46 +02:00
}
2018-09-04 21:56:27 +02:00
#[get("/local?<page>")]
2019-03-20 17:56:17 +01:00
pub fn local(
conn: DbConn,
user: Option<User>,
page: Option<Page>,
intl: I18n,
) -> Result<Ructe, ErrorPage> {
let page = page.unwrap_or_default();
let instance = Instance::get_local(&*conn)?;
let articles = Post::get_instance_page(&*conn, instance.id, page.limits())?;
Ok(render!(instance::local(
&(&*conn, &intl.catalog, user),
instance,
articles,
page.0,
Page::total(Post::count_local(&*conn)? as i32)
)))
2018-09-04 21:56:27 +02:00
}
2018-09-05 16:21:50 +02:00
#[get("/feed?<page>")]
pub fn feed(conn: DbConn, user: User, page: Option<Page>, intl: I18n) -> Result<Ructe, ErrorPage> {
let page = page.unwrap_or_default();
let followed = user.get_followed(&*conn)?;
let mut in_feed = followed.into_iter().map(|u| u.id).collect::<Vec<i32>>();
in_feed.push(user.id);
let articles = Post::user_feed_page(&*conn, in_feed, page.limits())?;
Ok(render!(instance::feed(
&(&*conn, &intl.catalog, Some(user)),
articles,
page.0,
Page::total(Post::count_local(&*conn)? as i32)
)))
}
#[get("/federated?<page>")]
2019-03-20 17:56:17 +01:00
pub fn federated(
conn: DbConn,
user: Option<User>,
page: Option<Page>,
intl: I18n,
) -> Result<Ructe, ErrorPage> {
let page = page.unwrap_or_default();
let articles = Post::get_recents_page(&*conn, page.limits())?;
Ok(render!(instance::federated(
&(&*conn, &intl.catalog, user),
articles,
page.0,
Page::total(Post::count_local(&*conn)? as i32)
)))
2018-09-05 16:21:50 +02:00
}
#[get("/admin")]
pub fn admin(conn: DbConn, admin: Admin, intl: I18n) -> Result<Ructe, ErrorPage> {
let local_inst = Instance::get_local(&*conn)?;
Ok(render!(instance::admin(
&(&*conn, &intl.catalog, Some(admin.0)),
local_inst.clone(),
InstanceSettingsForm {
name: local_inst.name.clone(),
open_registrations: local_inst.open_registrations,
short_description: local_inst.short_description,
long_description: local_inst.long_description,
default_license: local_inst.default_license,
},
ValidationErrors::default()
)))
}
#[derive(Clone, FromForm, Validate)]
pub struct InstanceSettingsForm {
#[validate(length(min = "1"))]
pub name: String,
pub open_registrations: bool,
pub short_description: SafeString,
pub long_description: SafeString,
#[validate(length(min = "1"))]
2019-03-20 17:56:17 +01:00
pub default_license: String,
}
#[post("/admin", data = "<form>")]
2019-03-20 17:56:17 +01:00
pub fn update_settings(
conn: DbConn,
admin: Admin,
form: LenientForm<InstanceSettingsForm>,
intl: I18n,
) -> Result<Redirect, Ructe> {
form.validate()
.and_then(|_| {
2019-03-20 17:56:17 +01:00
let instance = Instance::get_local(&*conn)
.expect("instance::update_settings: local instance error");
instance
.update(
&*conn,
form.name.clone(),
form.open_registrations,
form.short_description.clone(),
form.long_description.clone(),
)
.expect("instance::update_settings: save error");
Ok(Redirect::to(uri!(admin)))
})
2019-03-20 17:56:17 +01:00
.or_else(|e| {
let local_inst = Instance::get_local(&*conn)
.expect("instance::update_settings: local instance error");
Err(render!(instance::admin(
&(&*conn, &intl.catalog, Some(admin.0)),
local_inst,
form.clone(),
e
)))
})
}
#[get("/admin/instances?<page>")]
2019-03-20 17:56:17 +01:00
pub fn admin_instances(
admin: Admin,
conn: DbConn,
page: Option<Page>,
intl: I18n,
) -> Result<Ructe, ErrorPage> {
let page = page.unwrap_or_default();
let instances = Instance::page(&*conn, page.limits())?;
Ok(render!(instance::list(
&(&*conn, &intl.catalog, Some(admin.0)),
Instance::get_local(&*conn)?,
instances,
page.0,
Page::total(Instance::count(&*conn)? as i32)
)))
}
#[post("/admin/instances/<id>/block")]
pub fn toggle_block(_admin: Admin, conn: DbConn, id: i32) -> Result<Redirect, ErrorPage> {
if let Ok(inst) = Instance::get(&*conn, id) {
inst.toggle_block(&*conn)?;
}
Ok(Redirect::to(uri!(admin_instances: page = _)))
2018-09-09 12:25:55 +02:00
}
#[get("/admin/users?<page>")]
2019-03-20 17:56:17 +01:00
pub fn admin_users(
admin: Admin,
conn: DbConn,
page: Option<Page>,
intl: I18n,
) -> Result<Ructe, ErrorPage> {
let page = page.unwrap_or_default();
Ok(render!(instance::users(
&(&*conn, &intl.catalog, Some(admin.0)),
User::get_local_page(&*conn, page.limits())?,
page.0,
Page::total(User::count_local(&*conn)? as i32)
)))
2018-09-09 12:25:55 +02:00
}
#[post("/admin/users/<id>/ban")]
2019-03-20 17:56:17 +01:00
pub fn ban(
_admin: Admin,
conn: DbConn,
id: i32,
searcher: Searcher,
) -> Result<Redirect, ErrorPage> {
if let Ok(u) = User::get(&*conn, id) {
u.delete(&*conn, &searcher)?;
}
Ok(Redirect::to(uri!(admin_users: page = _)))
2018-09-09 12:25:55 +02:00
}
2018-05-13 19:39:18 +02:00
#[post("/inbox", data = "<data>")]
2019-03-20 17:56:17 +01:00
pub fn shared_inbox(
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
rockets: PlumeRocket,
data: inbox::SignedJson<serde_json::Value>,
2019-03-20 17:56:17 +01:00
headers: Headers,
) -> Result<String, status::BadRequest<&'static str>> {
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
inbox::handle_incoming(rockets, data, headers)
2018-05-13 19:39:18 +02:00
}
2018-06-10 21:33:42 +02:00
#[get("/nodeinfo/<version>")]
pub fn nodeinfo(conn: DbConn, version: String) -> Result<Json<serde_json::Value>, ErrorPage> {
if version != "2.0" && version != "2.1" {
return Err(ErrorPage::from(Error::NotFound));
}
let local_inst = Instance::get_local(&*conn)?;
let mut doc = json!({
"version": version,
2018-06-10 21:33:42 +02:00
"software": {
"name": env!("CARGO_PKG_NAME"),
"version": env!("CARGO_PKG_VERSION"),
2018-06-10 21:33:42 +02:00
},
"protocols": ["activitypub"],
"services": {
"inbound": [],
"outbound": []
},
"openRegistrations": local_inst.open_registrations,
2018-06-10 21:33:42 +02:00
"usage": {
"users": {
"total": User::count_local(&*conn)?
2018-06-10 21:33:42 +02:00
},
"localPosts": Post::count_local(&*conn)?,
"localComments": Comment::count_local(&*conn)?
2018-06-10 21:33:42 +02:00
},
"metadata": {
"nodeName": local_inst.name,
"nodeDescription": local_inst.short_description
}
});
if version == "2.1" {
doc["software"]["repository"] = json!(env!("CARGO_PKG_REPOSITORY"));
}
Ok(Json(doc))
2018-06-10 21:33:42 +02:00
}
2018-09-01 18:39:40 +02:00
#[get("/about")]
pub fn about(user: Option<User>, conn: DbConn, intl: I18n) -> Result<Ructe, ErrorPage> {
Ok(render!(instance::about(
&(&*conn, &intl.catalog, user),
Instance::get_local(&*conn)?,
Instance::get_local(&*conn)?.main_admin(&*conn)?,
User::count_local(&*conn)?,
Post::count_local(&*conn)?,
Instance::count(&*conn)? - 1
)))
2018-09-01 18:39:40 +02:00
}
2018-09-10 16:08:22 +02:00
#[get("/manifest.json")]
pub fn web_manifest(conn: DbConn) -> Result<Json<serde_json::Value>, ErrorPage> {
let instance = Instance::get_local(&*conn)?;
Ok(Json(json!({
2018-09-10 16:08:22 +02:00
"name": &instance.name,
"description": &instance.short_description,
"start_url": String::from("/"),
"scope": String::from("/"),
"display": String::from("standalone"),
"background_color": String::from("#f4f4f4"),
2018-10-09 20:38:01 +02:00
"theme_color": String::from("#7765e3"),
"categories": [String::from("social")],
"icons": CONFIG.logo.other.iter()
.map(|i| i.with_prefix(&uri!(static_files: file = "").to_string()))
.collect::<Vec<_>>()
})))
2018-09-10 16:08:22 +02:00
}