1
0
Fork 0
mirror of https://github.com/Nutomic/ibis.git synced 2024-11-22 02:21:10 +00:00

fix conflicts between federation and frontend routes

This commit is contained in:
Felix Ableitner 2024-01-19 15:49:08 +01:00
parent 469ca6f718
commit ccde4b4666
14 changed files with 123 additions and 55 deletions

1
Cargo.lock generated
View file

@ -1415,6 +1415,7 @@ dependencies = [
"sha2",
"time",
"tokio",
"tower",
"tower-http",
"tracing",
"url",

View file

@ -65,6 +65,7 @@ wasm-bindgen = "0.2.89"
console_error_panic_hook = "0.1.7"
console_log = "1.0.0"
time = "0.3.31"
tower = "0.4.13"
[dev-dependencies]
pretty_assertions = "1.4.0"

View file

@ -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
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
trunk serve -w src/frontend/

View file

@ -43,7 +43,6 @@ pub(super) async fn resolve_instance(
data: Data<MyDataHandle>,
) -> MyResult<Json<DbInstance>> {
// TODO: workaround because axum makes it hard to have multiple routes on /
let id = format!("{}instance", query.id);
let instance: DbInstance = ObjectId::parse(&id)?.dereference(&data).await?;
let instance: DbInstance = ObjectId::from(query.id).dereference(&data).await?;
Ok(Json(instance))
}

View file

@ -33,7 +33,6 @@ impl Follow {
kind: Default::default(),
id,
};
send_activity(&actor, follow, vec![to.shared_inbox_or_inbox()], data).await?;
Ok(())
}

View file

@ -35,9 +35,7 @@ use url::Url;
pub fn federation_routes() -> Router {
Router::new()
// TODO: would be nice if this could be at / but axum doesnt properly support routing by headers
// https://github.com/tokio-rs/axum/issues/1654
.route("/instance", get(http_get_instance))
.route("/", get(http_get_instance))
.route("/user/:name", get(http_get_person))
.route("/all_articles", get(http_get_all_articles))
.route("/article/:title", get(http_get_article))

View file

@ -11,7 +11,10 @@ use activitypub_federation::fetch::collection_id::CollectionId;
use activitypub_federation::fetch::object_id::ObjectId;
use activitypub_federation::http_signatures::generate_actor_keypair;
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 diesel::Connection;
use diesel::PgConnection;
@ -23,6 +26,7 @@ use leptos_axum::{generate_route_list, LeptosRoutes};
use log::info;
use std::net::ToSocketAddrs;
use std::sync::{Arc, Mutex};
use tower::Layer;
use tower_http::cors::CorsLayer;
use tower_http::services::{ServeDir, ServeFile};
@ -34,6 +38,8 @@ mod utils;
const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");
const FEDERATION_ROUTES_PREFIX: &str = "/federation_routes";
pub async fn start(hostname: &str, database_url: &str) -> MyResult<()> {
let db_connection = Arc::new(Mutex::new(PgConnection::establish(database_url)?));
db_connection
@ -53,8 +59,7 @@ pub async fn start(hostname: &str, database_url: &str) -> MyResult<()> {
// Create local instance if it doesnt exist yet
// TODO: Move this into setup api call
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://{}/instance", hostname))?;
let ap_id = ObjectId::parse(&format!("http://{hostname}"))?;
let articles_url = CollectionId::parse(&format!("http://{}/all_articles", hostname))?;
let inbox_url = format!("http://{}/inbox", hostname);
let keypair = generate_actor_keypair()?;
@ -102,13 +107,44 @@ pub async fn start(hostname: &str, database_url: &str) -> MyResult<()> {
"/pkg/ibis_bg.wasm",
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())
.layer(FederationMiddleware::new(config))
.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}");
Server::bind(&addr).serve(app.into_make_service()).await?;
Server::bind(&addr)
.serve(app_with_middleware.into_make_service())
.await?;
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
}

View file

@ -1,8 +1,9 @@
use crate::common::LocalUserView;
use crate::frontend::api::ApiClient;
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::read_article::ReadArticle;
use crate::frontend::pages::register::Register;
use crate::frontend::pages::Page;
use leptos::{
@ -73,7 +74,9 @@ pub fn App() -> impl IntoView {
<Nav />
<main>
<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::Register.path()} view=Register/>
</Routes>

View file

@ -2,7 +2,7 @@ pub mod api;
pub mod app;
mod components;
pub mod error;
mod pages;
pub mod pages;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]

View file

@ -1,47 +1,16 @@
use crate::common::GetArticleData;
use crate::frontend::app::GlobalState;
use leptos::*;
use leptos_router::*;
#[component]
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! {
<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>
<nav class="inner">
<li>
<A href="read">"Read"</A>
</li>
<li>
<A href="edit">"Edit"</A>
</li>
</nav>
}
}

View file

@ -0,0 +1,11 @@
use leptos::*;
#[component]
pub fn EditArticle() -> impl IntoView {
view! {
<div class="item-view">
<h1>Title...</h1>
<textarea></textarea>
</div>
}
}

View file

@ -1,5 +1,7 @@
pub mod article;
pub mod edit_article;
pub mod login;
pub mod read_article;
pub mod register;
#[derive(Debug, Clone, Copy, Default)]

View 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>
}
}

View file

@ -3,14 +3,14 @@ use ibis_lib::backend::start;
use ibis_lib::common::RegisterUserData;
use ibis_lib::frontend::api::ApiClient;
use ibis_lib::frontend::error::MyResult;
use reqwest::cookie::Jar;
use reqwest::ClientBuilder;
use std::env::current_dir;
use std::fs::create_dir_all;
use std::ops::Deref;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Arc;
use std::sync::Once;
use std::thread::{sleep, spawn};
use std::time::Duration;