Plume/src/main.rs

291 lines
9.9 KiB
Rust
Raw Permalink Normal View History

#![allow(clippy::too_many_arguments)]
2021-11-27 22:53:13 +00:00
#![feature(decl_macro, proc_macro_hygiene)]
2018-09-02 20:55:42 +00:00
#[macro_use]
extern crate gettext_macros;
#[macro_use]
extern crate rocket;
#[macro_use]
2018-04-23 15:09:05 +00:00
extern crate serde_json;
use clap::App;
2018-10-06 11:06:02 +00:00
use diesel::r2d2::ConnectionManager;
use plume_models::{
db_conn::{DbPool, PragmaForeignKey},
instance::Instance,
migrations::IMPORTED_MIGRATIONS,
2021-01-31 15:50:48 +00:00
remote_fetch_actor::RemoteFetchActor,
2021-01-06 19:56:35 +00:00
search::{actor::SearchActor, Searcher as UnmanagedSearcher},
Connection, CONFIG,
};
2019-03-20 16:56:17 +00:00
use rocket_csrf::CsrfFairingBuilder;
use scheduled_thread_pool::ScheduledThreadPool;
use std::process::exit;
use std::sync::{Arc, Mutex};
use std::time::Duration;
2021-01-10 23:38:41 +00:00
use tracing::warn;
2019-04-19 12:59:03 +00:00
init_i18n!(
2022-01-26 13:15:35 +00:00
"plume", af, ar, bg, ca, cs, cy, da, de, el, en, eo, es, eu, fa, fi, fr, gl, he, hi, hr, hu,
it, ja, ko, nb, nl, no, pl, pt, ro, ru, sat, si, sk, sl, sr, sv, tr, uk, vi, zh
2019-04-19 12:59:03 +00:00
);
2018-09-19 14:49:34 +00:00
mod api;
mod inbox;
mod mail;
mod utils;
#[macro_use]
mod template_utils;
mod routes;
#[macro_use]
extern crate shrinkwraprs;
#[cfg(feature = "test")]
mod test_routes;
include!(concat!(env!("OUT_DIR"), "/templates.rs"));
compile_i18n!();
2018-10-06 11:06:02 +00:00
/// Initializes a database pool.
fn init_pool() -> Option<DbPool> {
let manager = ConnectionManager::<Connection>::new(CONFIG.database_url.as_str());
let mut builder = DbPool::builder()
.connection_customizer(Box::new(PragmaForeignKey))
.min_idle(CONFIG.db_min_idle);
if let Some(max_size) = CONFIG.db_max_size {
builder = builder.max_size(max_size);
};
let pool = builder.build(manager).ok()?;
2021-11-24 13:07:25 +00:00
let conn = pool.get().unwrap();
Instance::cache_local(&conn);
let _ = Instance::create_local_instance_user(&conn);
2021-11-24 13:07:25 +00:00
Instance::cache_local_instance_user(&conn);
Some(pool)
2018-10-06 11:06:02 +00:00
}
pub(crate) fn init_rocket() -> rocket::Rocket {
match dotenv::dotenv() {
Ok(path) => eprintln!("Configuration read from {}", path.display()),
Err(ref e) if e.not_found() => eprintln!("no .env was found"),
e => e.map(|_| ()).unwrap(),
}
2021-01-11 00:15:34 +00:00
tracing_subscriber::fmt::init();
App::new("Plume")
.bin_name("plume")
.version(env!("CARGO_PKG_VERSION"))
.about("Plume backend server")
.after_help(
r#"
The plume command should be run inside the directory
containing the `.env` configuration file and `static` directory.
See https://docs.joinplu.me/installation/config
and https://docs.joinplu.me/installation/init for more info.
"#,
)
.get_matches();
let dbpool = init_pool().expect("main: database pool initialization error");
if IMPORTED_MIGRATIONS
.is_pending(&dbpool.get().unwrap())
.unwrap_or(true)
{
panic!(
r#"
It appear your database migration does not run the migration required
by this version of Plume. To fix this, you can run migrations via
this command:
plm migration run
Then try to restart Plume.
"#
)
}
let workpool = ScheduledThreadPool::with_name("worker {}", num_cpus::get());
// we want a fast exit here, so
let searcher = Arc::new(UnmanagedSearcher::open_or_recreate(
&CONFIG.search_index,
&CONFIG.search_tokenizers,
));
2021-01-31 15:50:48 +00:00
RemoteFetchActor::init(dbpool.clone());
2021-01-06 19:56:35 +00:00
SearchActor::init(searcher.clone(), dbpool.clone());
let commiter = searcher.clone();
2019-03-20 16:56:17 +00:00
workpool.execute_with_fixed_delay(
Duration::from_secs(5),
Duration::from_secs(60 * 30),
move || commiter.commit(),
);
let search_unlocker = searcher.clone();
ctrlc::set_handler(move || {
search_unlocker.commit();
search_unlocker.drop_writer();
exit(0);
2019-03-20 16:56:17 +00:00
})
.expect("Error setting Ctrl-c handler");
let mail = mail::init();
if mail.is_none() && CONFIG.rocket.as_ref().unwrap().environment.is_prod() {
warn!("Warning: the email server is not configured (or not completely).");
warn!("Please refer to the documentation to see how to configure it.");
}
2021-01-24 10:49:49 +00:00
rocket::custom(CONFIG.rocket.clone().unwrap())
2019-03-20 16:56:17 +00:00
.mount(
"/",
routes![
routes::blogs::details,
routes::blogs::activity_details,
routes::blogs::outbox,
routes::blogs::outbox_page,
2019-03-20 16:56:17 +00:00
routes::blogs::new,
routes::blogs::new_auth,
routes::blogs::create,
routes::blogs::delete,
routes::blogs::edit,
routes::blogs::update,
2019-03-20 16:56:17 +00:00
routes::blogs::atom_feed,
routes::comments::create,
routes::comments::delete,
routes::comments::activity_pub,
2022-01-06 11:18:20 +00:00
routes::email_signups::create,
routes::email_signups::created,
routes::email_signups::show,
routes::email_signups::signup,
2019-03-20 16:56:17 +00:00
routes::instance::index,
routes::instance::admin,
routes::instance::admin_mod,
2019-03-20 16:56:17 +00:00
routes::instance::admin_instances,
routes::instance::admin_users,
2023-03-19 16:00:02 +00:00
routes::instance::admin_search_users,
routes::instance::admin_email_blocklist,
routes::instance::add_email_blocklist,
routes::instance::delete_email_blocklist,
routes::instance::edit_users,
2019-03-20 16:56:17 +00:00
routes::instance::toggle_block,
routes::instance::update_settings,
routes::instance::shared_inbox,
routes::instance::interact,
2019-03-20 16:56:17 +00:00
routes::instance::nodeinfo,
routes::instance::about,
routes::instance::privacy,
2019-03-20 16:56:17 +00:00
routes::instance::web_manifest,
routes::likes::create,
routes::likes::create_auth,
routes::medias::list,
routes::medias::new,
routes::medias::upload,
routes::medias::details,
routes::medias::delete,
routes::medias::set_avatar,
routes::notifications::notifications,
routes::notifications::notifications_auth,
routes::posts::details,
routes::posts::activity_details,
routes::posts::edit,
routes::posts::update,
routes::posts::new,
routes::posts::new_auth,
routes::posts::create,
routes::posts::delete,
routes::posts::remote_interact,
routes::posts::remote_interact_post,
2019-03-20 16:56:17 +00:00
routes::reshares::create,
routes::reshares::create_auth,
routes::search::search,
routes::session::new,
routes::session::create,
routes::session::delete,
routes::session::password_reset_request_form,
routes::session::password_reset_request,
routes::session::password_reset_form,
routes::session::password_reset,
routes::theme_files,
2019-03-20 16:56:17 +00:00
routes::plume_static_files,
routes::static_files,
routes::plume_media_files,
2019-03-20 16:56:17 +00:00
routes::tags::tag,
Add support for generic timeline (#525) * Begin adding support for timeline * fix some bugs with parser * fmt * add error reporting for parser * add tests for timeline query parser * add rejection tests for parse * begin adding support for lists also run migration before compiling, so schema.rs is up to date * add sqlite migration * end adding lists still miss tests and query integration * cargo fmt * try to add some tests * Add some constraint to db, and fix list test and refactor other tests to use begin_transaction * add more tests for lists * add support for lists in query executor * add keywords for including/excluding boosts and likes * cargo fmt * add function to list lists used by query will make it easier to warn users when creating timeline with unknown lists * add lang support * add timeline creation error message when using unexisting lists * Update .po files * WIP: interface for timelines * don't use diesel for migrations not sure how it passed the ci on the other branch * add some tests for timeline add an int representing the order of timelines (first one will be on top, second just under...) use first() instead of limit(1).get().into_iter().nth(0) remove migrations from build artifacts as they are now compiled in * cargo fmt * remove timeline order * fix tests * add tests for timeline creation failure * cargo fmt * add tests for timelines * add test for matching direct lists and keywords * add test for language filtering * Add a more complex test for Timeline::matches, and fix TQ::matches for TQ::Or * Make the main crate compile + FMT * Use the new timeline system - Replace the old "feed" system with timelines - Display all timelines someone can access on their home page (either their personal ones, or instance timelines) - Remove functions that were used to get user/local/federated feed - Add new posts to timelines - Create a default timeline called "My feed" for everyone, and "Local feed"/"Federated feed" with timelines @fdb-hiroshima I don't know if that's how you pictured it? If you imagined it differently I can of course make changes. I hope I didn't forgot anything… * Cargo fmt * Try to fix the migration * Fix tests * Fix the test (for real this time ?) * Fix the tests ? + fmt * Use Kind::Like and Kind::Reshare when needed * Forgot to run cargo fmt once again * revert translations * fix reviewed stuff * reduce code duplication by macros * cargo fmt
2019-10-07 17:08:20 +00:00
routes::timelines::details,
routes::timelines::new,
routes::timelines::create,
routes::timelines::edit,
routes::timelines::update,
routes::timelines::delete,
2019-03-20 16:56:17 +00:00
routes::user::me,
routes::user::details,
routes::user::dashboard,
routes::user::dashboard_auth,
routes::user::followers,
routes::user::followed,
routes::user::edit,
routes::user::edit_auth,
routes::user::update,
routes::user::delete,
routes::user::follow,
routes::user::follow_not_connected,
2019-03-20 16:56:17 +00:00
routes::user::follow_auth,
routes::user::activity_details,
routes::user::outbox,
routes::user::outbox_page,
2019-03-20 16:56:17 +00:00
routes::user::inbox,
routes::user::ap_followers,
routes::user::new,
routes::user::create,
routes::user::atom_feed,
routes::well_known::host_meta,
routes::well_known::nodeinfo,
routes::well_known::webfinger,
routes::errors::csrf_violation
],
)
.mount(
"/api/v1",
routes![
api::oauth,
api::apps::create,
api::posts::get,
api::posts::list,
api::posts::create,
api::posts::delete,
2019-03-20 16:56:17 +00:00
],
)
.register(catchers![
2018-06-18 15:59:49 +00:00
routes::errors::not_found,
routes::errors::unprocessable_entity,
2018-06-18 15:59:49 +00:00
routes::errors::server_error
])
.manage(Arc::new(Mutex::new(mail)))
.manage::<Arc<Mutex<Vec<routes::session::ResetRequest>>>>(Arc::new(Mutex::new(vec![])))
.manage(dbpool)
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 17:31:47 +00:00
.manage(Arc::new(workpool))
.manage(searcher)
.manage(include_i18n!())
2019-03-20 16:56:17 +00:00
.attach(
CsrfFairingBuilder::new()
.set_default_target(
"/csrf-violation?target=<uri>".to_owned(),
rocket::http::Method::Post,
)
.add_exceptions(vec![
("/inbox".to_owned(), "/inbox".to_owned(), None),
2019-03-20 16:56:17 +00:00
(
"/@/<name>/inbox".to_owned(),
"/@/<name>/inbox".to_owned(),
None,
2019-03-20 16:56:17 +00:00
),
("/api/<path..>".to_owned(), "/api/<path..>".to_owned(), None),
])
2019-03-20 16:56:17 +00:00
.finalize()
.expect("main: csrf fairing creation error"),
2021-01-24 10:49:49 +00:00
)
}
fn main() {
let rocket = init_rocket();
#[cfg(feature = "test")]
let rocket = rocket.mount("/test", routes![test_routes::health,]);
2021-01-24 10:49:49 +00:00
rocket.launch();
}