mirror of
https://github.com/Nutomic/ibis.git
synced 2024-11-22 14:21:09 +00:00
fix conflicts between federation and frontend routes
This commit is contained in:
parent
469ca6f718
commit
ccde4b4666
14 changed files with 123 additions and 55 deletions
1
Cargo.lock
generated
1
Cargo.lock
generated
|
@ -1415,6 +1415,7 @@ dependencies = [
|
||||||
"sha2",
|
"sha2",
|
||||||
"time",
|
"time",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"tower",
|
||||||
"tower-http",
|
"tower-http",
|
||||||
"tracing",
|
"tracing",
|
||||||
"url",
|
"url",
|
||||||
|
|
|
@ -65,6 +65,7 @@ wasm-bindgen = "0.2.89"
|
||||||
console_error_panic_hook = "0.1.7"
|
console_error_panic_hook = "0.1.7"
|
||||||
console_log = "1.0.0"
|
console_log = "1.0.0"
|
||||||
time = "0.3.31"
|
time = "0.3.31"
|
||||||
|
tower = "0.4.13"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
pretty_assertions = "1.4.0"
|
pretty_assertions = "1.4.0"
|
||||||
|
|
|
@ -13,6 +13,8 @@ You need to install [cargo](https://rustup.rs/) and [trunk](https://trunkrs.dev)
|
||||||
```
|
```
|
||||||
# start backend, with separate target folder to avoid rebuilds from arch change
|
# start backend, with separate target folder to avoid rebuilds from arch change
|
||||||
cargo run --target-dir target/backend
|
cargo run --target-dir target/backend
|
||||||
|
# or with automatic rebuild on changes using cargo-watch
|
||||||
|
CARGO_TARGET_DIR=target/backend cargo watch -c -x run
|
||||||
|
|
||||||
# start frontend, automatic rebuild on changes
|
# start frontend, automatic rebuild on changes
|
||||||
trunk serve -w src/frontend/
|
trunk serve -w src/frontend/
|
||||||
|
|
|
@ -43,7 +43,6 @@ pub(super) async fn resolve_instance(
|
||||||
data: Data<MyDataHandle>,
|
data: Data<MyDataHandle>,
|
||||||
) -> MyResult<Json<DbInstance>> {
|
) -> MyResult<Json<DbInstance>> {
|
||||||
// TODO: workaround because axum makes it hard to have multiple routes on /
|
// TODO: workaround because axum makes it hard to have multiple routes on /
|
||||||
let id = format!("{}instance", query.id);
|
let instance: DbInstance = ObjectId::from(query.id).dereference(&data).await?;
|
||||||
let instance: DbInstance = ObjectId::parse(&id)?.dereference(&data).await?;
|
|
||||||
Ok(Json(instance))
|
Ok(Json(instance))
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,7 +33,6 @@ impl Follow {
|
||||||
kind: Default::default(),
|
kind: Default::default(),
|
||||||
id,
|
id,
|
||||||
};
|
};
|
||||||
|
|
||||||
send_activity(&actor, follow, vec![to.shared_inbox_or_inbox()], data).await?;
|
send_activity(&actor, follow, vec![to.shared_inbox_or_inbox()], data).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -35,9 +35,7 @@ use url::Url;
|
||||||
|
|
||||||
pub fn federation_routes() -> Router {
|
pub fn federation_routes() -> Router {
|
||||||
Router::new()
|
Router::new()
|
||||||
// TODO: would be nice if this could be at / but axum doesnt properly support routing by headers
|
.route("/", get(http_get_instance))
|
||||||
// https://github.com/tokio-rs/axum/issues/1654
|
|
||||||
.route("/instance", get(http_get_instance))
|
|
||||||
.route("/user/:name", get(http_get_person))
|
.route("/user/:name", get(http_get_person))
|
||||||
.route("/all_articles", get(http_get_all_articles))
|
.route("/all_articles", get(http_get_all_articles))
|
||||||
.route("/article/:title", get(http_get_article))
|
.route("/article/:title", get(http_get_article))
|
||||||
|
|
|
@ -11,7 +11,10 @@ use activitypub_federation::fetch::collection_id::CollectionId;
|
||||||
use activitypub_federation::fetch::object_id::ObjectId;
|
use activitypub_federation::fetch::object_id::ObjectId;
|
||||||
use activitypub_federation::http_signatures::generate_actor_keypair;
|
use activitypub_federation::http_signatures::generate_actor_keypair;
|
||||||
use api::api_routes;
|
use api::api_routes;
|
||||||
use axum::{Router, Server};
|
use axum::http::{HeaderValue, Request};
|
||||||
|
use axum::Server;
|
||||||
|
use axum::ServiceExt;
|
||||||
|
use axum::{middleware::Next, response::Response, Router};
|
||||||
use chrono::Local;
|
use chrono::Local;
|
||||||
use diesel::Connection;
|
use diesel::Connection;
|
||||||
use diesel::PgConnection;
|
use diesel::PgConnection;
|
||||||
|
@ -23,6 +26,7 @@ use leptos_axum::{generate_route_list, LeptosRoutes};
|
||||||
use log::info;
|
use log::info;
|
||||||
use std::net::ToSocketAddrs;
|
use std::net::ToSocketAddrs;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tower::Layer;
|
||||||
use tower_http::cors::CorsLayer;
|
use tower_http::cors::CorsLayer;
|
||||||
use tower_http::services::{ServeDir, ServeFile};
|
use tower_http::services::{ServeDir, ServeFile};
|
||||||
|
|
||||||
|
@ -34,6 +38,8 @@ mod utils;
|
||||||
|
|
||||||
const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");
|
const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");
|
||||||
|
|
||||||
|
const FEDERATION_ROUTES_PREFIX: &str = "/federation_routes";
|
||||||
|
|
||||||
pub async fn start(hostname: &str, database_url: &str) -> MyResult<()> {
|
pub async fn start(hostname: &str, database_url: &str) -> MyResult<()> {
|
||||||
let db_connection = Arc::new(Mutex::new(PgConnection::establish(database_url)?));
|
let db_connection = Arc::new(Mutex::new(PgConnection::establish(database_url)?));
|
||||||
db_connection
|
db_connection
|
||||||
|
@ -53,8 +59,7 @@ pub async fn start(hostname: &str, database_url: &str) -> MyResult<()> {
|
||||||
// Create local instance if it doesnt exist yet
|
// Create local instance if it doesnt exist yet
|
||||||
// TODO: Move this into setup api call
|
// TODO: Move this into setup api call
|
||||||
if DbInstance::read_local_instance(&config.db_connection).is_err() {
|
if DbInstance::read_local_instance(&config.db_connection).is_err() {
|
||||||
// TODO: workaround because axum makes it hard to have multiple routes on /
|
let ap_id = ObjectId::parse(&format!("http://{hostname}"))?;
|
||||||
let ap_id = ObjectId::parse(&format!("http://{}/instance", hostname))?;
|
|
||||||
let articles_url = CollectionId::parse(&format!("http://{}/all_articles", hostname))?;
|
let articles_url = CollectionId::parse(&format!("http://{}/all_articles", hostname))?;
|
||||||
let inbox_url = format!("http://{}/inbox", hostname);
|
let inbox_url = format!("http://{}/inbox", hostname);
|
||||||
let keypair = generate_actor_keypair()?;
|
let keypair = generate_actor_keypair()?;
|
||||||
|
@ -102,13 +107,44 @@ pub async fn start(hostname: &str, database_url: &str) -> MyResult<()> {
|
||||||
"/pkg/ibis_bg.wasm",
|
"/pkg/ibis_bg.wasm",
|
||||||
ServeFile::new_with_mime("assets/dist/ibis_bg.wasm", &"application/wasm".parse()?),
|
ServeFile::new_with_mime("assets/dist/ibis_bg.wasm", &"application/wasm".parse()?),
|
||||||
)
|
)
|
||||||
.nest("", federation_routes())
|
.nest(FEDERATION_ROUTES_PREFIX, federation_routes())
|
||||||
.nest("/api/v1", api_routes())
|
.nest("/api/v1", api_routes())
|
||||||
.layer(FederationMiddleware::new(config))
|
.layer(FederationMiddleware::new(config))
|
||||||
.layer(CorsLayer::permissive());
|
.layer(CorsLayer::permissive());
|
||||||
|
|
||||||
|
// Rewrite federation routes
|
||||||
|
// https://docs.rs/axum/0.7.4/axum/middleware/index.html#rewriting-request-uri-in-middleware
|
||||||
|
let middleware = axum::middleware::from_fn(federation_routes_middleware);
|
||||||
|
let app_with_middleware = middleware.layer(app);
|
||||||
|
|
||||||
info!("{addr}");
|
info!("{addr}");
|
||||||
Server::bind(&addr).serve(app.into_make_service()).await?;
|
Server::bind(&addr)
|
||||||
|
.serve(app_with_middleware.into_make_service())
|
||||||
|
.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rewrite federation routes to use `FEDERATION_ROUTES_PREFIX`, to avoid conflicts
|
||||||
|
/// with frontend routes. If a request is an Activitypub fetch as indicated by
|
||||||
|
/// `Accept: application/activity+json` header, use the federation routes. Otherwise
|
||||||
|
/// leave the path unchanged so it can go to frontend.
|
||||||
|
async fn federation_routes_middleware<B>(request: Request<B>, next: Next<B>) -> Response {
|
||||||
|
let (mut parts, body) = request.into_parts();
|
||||||
|
// rewrite uri based on accept header
|
||||||
|
let mut uri = parts.uri.to_string();
|
||||||
|
let accept_value = HeaderValue::from_static("application/activity+json");
|
||||||
|
if Some(&accept_value) == parts.headers.get("Accept")
|
||||||
|
|| Some(&accept_value) == parts.headers.get("Content-Type")
|
||||||
|
{
|
||||||
|
uri = format!("{FEDERATION_ROUTES_PREFIX}{uri}");
|
||||||
|
}
|
||||||
|
// drop trailing slash
|
||||||
|
if uri.ends_with('/') {
|
||||||
|
uri.pop();
|
||||||
|
}
|
||||||
|
parts.uri = uri.parse().unwrap();
|
||||||
|
let request = Request::from_parts(parts, body);
|
||||||
|
|
||||||
|
next.run(request).await
|
||||||
|
}
|
||||||
|
|
|
@ -1,8 +1,9 @@
|
||||||
use crate::common::LocalUserView;
|
use crate::common::LocalUserView;
|
||||||
use crate::frontend::api::ApiClient;
|
use crate::frontend::api::ApiClient;
|
||||||
use crate::frontend::components::nav::Nav;
|
use crate::frontend::components::nav::Nav;
|
||||||
use crate::frontend::pages::article::Article;
|
use crate::frontend::pages::edit_article::EditArticle;
|
||||||
use crate::frontend::pages::login::Login;
|
use crate::frontend::pages::login::Login;
|
||||||
|
use crate::frontend::pages::read_article::ReadArticle;
|
||||||
use crate::frontend::pages::register::Register;
|
use crate::frontend::pages::register::Register;
|
||||||
use crate::frontend::pages::Page;
|
use crate::frontend::pages::Page;
|
||||||
use leptos::{
|
use leptos::{
|
||||||
|
@ -73,7 +74,9 @@ pub fn App() -> impl IntoView {
|
||||||
<Nav />
|
<Nav />
|
||||||
<main>
|
<main>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path={Page::Home.path()} view=Article/>
|
<Route path={Page::Home.path()} view=ReadArticle/>
|
||||||
|
<Route path="/article/:title" view=ReadArticle/>
|
||||||
|
<Route path="/article/:title/edit" view=EditArticle/>
|
||||||
<Route path={Page::Login.path()} view=Login/>
|
<Route path={Page::Login.path()} view=Login/>
|
||||||
<Route path={Page::Register.path()} view=Register/>
|
<Route path={Page::Register.path()} view=Register/>
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|
|
@ -2,7 +2,7 @@ pub mod api;
|
||||||
pub mod app;
|
pub mod app;
|
||||||
mod components;
|
mod components;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
mod pages;
|
pub mod pages;
|
||||||
|
|
||||||
#[cfg(feature = "hydrate")]
|
#[cfg(feature = "hydrate")]
|
||||||
#[wasm_bindgen::prelude::wasm_bindgen]
|
#[wasm_bindgen::prelude::wasm_bindgen]
|
||||||
|
|
|
@ -1,47 +1,16 @@
|
||||||
use crate::common::GetArticleData;
|
|
||||||
use crate::frontend::app::GlobalState;
|
|
||||||
use leptos::*;
|
use leptos::*;
|
||||||
use leptos_router::*;
|
use leptos_router::*;
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
pub fn Article() -> impl IntoView {
|
pub fn Article() -> impl IntoView {
|
||||||
let params = use_params_map();
|
|
||||||
let article = create_resource(
|
|
||||||
move || {
|
|
||||||
params
|
|
||||||
.get()
|
|
||||||
.get("title")
|
|
||||||
.cloned()
|
|
||||||
.unwrap_or("Main Page".to_string())
|
|
||||||
},
|
|
||||||
move |title| async move {
|
|
||||||
GlobalState::api_client()
|
|
||||||
.get_article(GetArticleData {
|
|
||||||
title: Some(title),
|
|
||||||
instance_id: None,
|
|
||||||
id: None,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
let global_state = use_context::<RwSignal<GlobalState>>().unwrap();
|
|
||||||
let (count, set_count) = create_signal(0);
|
|
||||||
view! {
|
view! {
|
||||||
<Suspense fallback=|| view! { "Loading..." }>
|
<nav class="inner">
|
||||||
{move || article.get().map(|article|
|
<li>
|
||||||
view! {
|
<A href="read">"Read"</A>
|
||||||
<div class="item-view">
|
</li>
|
||||||
<h1>{article.article.title}</h1>
|
<li>
|
||||||
<Show when=move || global_state.with(|state| state.my_profile.is_some())>
|
<A href="edit">"Edit"</A>
|
||||||
<button on:click=move |_| {
|
</li>
|
||||||
set_count.update(|n| *n += 1);
|
</nav>
|
||||||
}>Edit {move || count.get()}</button>
|
|
||||||
</Show>
|
|
||||||
<div>{article.article.text}</div>
|
|
||||||
</div>
|
|
||||||
})}
|
|
||||||
</Suspense>
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
11
src/frontend/pages/edit_article.rs
Normal file
11
src/frontend/pages/edit_article.rs
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
use leptos::*;
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn EditArticle() -> impl IntoView {
|
||||||
|
view! {
|
||||||
|
<div class="item-view">
|
||||||
|
<h1>Title...</h1>
|
||||||
|
<textarea></textarea>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,5 +1,7 @@
|
||||||
pub mod article;
|
pub mod article;
|
||||||
|
pub mod edit_article;
|
||||||
pub mod login;
|
pub mod login;
|
||||||
|
pub mod read_article;
|
||||||
pub mod register;
|
pub mod register;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Default)]
|
#[derive(Debug, Clone, Copy, Default)]
|
||||||
|
|
47
src/frontend/pages/read_article.rs
Normal file
47
src/frontend/pages/read_article.rs
Normal file
|
@ -0,0 +1,47 @@
|
||||||
|
use crate::common::GetArticleData;
|
||||||
|
use crate::frontend::app::GlobalState;
|
||||||
|
use leptos::*;
|
||||||
|
use leptos_router::*;
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn ReadArticle() -> impl IntoView {
|
||||||
|
let params = use_params_map();
|
||||||
|
let article = create_resource(
|
||||||
|
move || {
|
||||||
|
params
|
||||||
|
.get()
|
||||||
|
.get("title")
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or("Main_Page".to_string())
|
||||||
|
},
|
||||||
|
move |title| async move {
|
||||||
|
GlobalState::api_client()
|
||||||
|
.get_article(GetArticleData {
|
||||||
|
title: Some(title),
|
||||||
|
instance_id: None,
|
||||||
|
id: None,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let global_state = use_context::<RwSignal<GlobalState>>().unwrap();
|
||||||
|
let (count, set_count) = create_signal(0);
|
||||||
|
view! {
|
||||||
|
<Suspense fallback=|| view! { "Loading..." }>
|
||||||
|
{move || article.get().map(|article|
|
||||||
|
view! {
|
||||||
|
<div class="item-view">
|
||||||
|
<h1>{article.article.title}</h1>
|
||||||
|
<Show when=move || global_state.with(|state| state.my_profile.is_some())>
|
||||||
|
<button on:click=move |_| {
|
||||||
|
set_count.update(|n| *n += 1);
|
||||||
|
}>Edit {move || count.get()}</button>
|
||||||
|
</Show>
|
||||||
|
<div>{article.article.text}</div>
|
||||||
|
</div>
|
||||||
|
})}
|
||||||
|
</Suspense>
|
||||||
|
}
|
||||||
|
}
|
|
@ -3,14 +3,14 @@ use ibis_lib::backend::start;
|
||||||
use ibis_lib::common::RegisterUserData;
|
use ibis_lib::common::RegisterUserData;
|
||||||
use ibis_lib::frontend::api::ApiClient;
|
use ibis_lib::frontend::api::ApiClient;
|
||||||
use ibis_lib::frontend::error::MyResult;
|
use ibis_lib::frontend::error::MyResult;
|
||||||
use reqwest::cookie::Jar;
|
|
||||||
use reqwest::ClientBuilder;
|
use reqwest::ClientBuilder;
|
||||||
use std::env::current_dir;
|
use std::env::current_dir;
|
||||||
use std::fs::create_dir_all;
|
use std::fs::create_dir_all;
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use std::process::{Command, Stdio};
|
use std::process::{Command, Stdio};
|
||||||
use std::sync::atomic::{AtomicI32, Ordering};
|
use std::sync::atomic::{AtomicI32, Ordering};
|
||||||
use std::sync::Arc;
|
|
||||||
use std::sync::Once;
|
use std::sync::Once;
|
||||||
use std::thread::{sleep, spawn};
|
use std::thread::{sleep, spawn};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
Loading…
Reference in a new issue