//! Pages (hub spec §6): the router, the shell every template extends, the //! error page, and askama filters. Handlers are thin: they resolve names, //! call the view layer under the repository lock, and render. pub mod filters; mod history; mod home; mod refs; mod repo; mod statics; use crate::repos::RepoError; use crate::{db, Shared}; use askama::Template; use axum::extract::DefaultBodyLimit; use axum::http::{header, StatusCode}; use axum::response::{Html, IntoResponse, Response}; use axum::routing::{any, get}; use axum::Router; use tower_http::compression::CompressionLayer; use tower_http::trace::TraceLayer; pub fn router(app: Shared) -> Router { let push_limit = app.config.limits.push_body_limit.0 as usize; Router::new() .route("/", get(home::index)) .route("/explore", get(home::explore)) .route("/health", get(home::health)) .route("/.well-known/oxyhub-key", get(home::hub_key)) .route("/style.css", get(statics::style)) .route("/favicon.svg", get(statics::favicon)) .route("/favicon.ico", get(statics::favicon)) .route("/static/{*path}", get(statics::asset)) .nest("/api/v1", crate::api::router()) .route("/{owner}", get(home::owner)) .route("/{owner}/{name}", get(repo::overview)) .route("/{owner}/{name}/tree/{r}", get(repo::tree_root)) .route("/{owner}/{name}/tree/{r}/{*path}", get(repo::tree)) .route("/{owner}/{name}/file/{r}/{*path}", get(repo::file)) .route("/{owner}/{name}/last/{r}", get(repo::last_changes)) .route("/{owner}/{name}/changes/{r}", get(history::history)) .route("/{owner}/{name}/change/{hash}", get(history::change)) .route("/{owner}/{name}/compare/{spec}", get(history::compare)) .route("/{owner}/{name}/bookmarks", get(refs::bookmarks)) .route("/{owner}/{name}/tags", get(refs::tags)) .route("/{owner}/{name}/conflicts", get(refs::conflicts)) .route("/{owner}/{name}/trust", get(refs::trust)) .route("/{owner}/{name}/pushes", get(refs::pushes)) .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit))) .fallback(not_found) .layer(CompressionLayer::new()) .layer(TraceLayer::new_for_http()) .with_state(app) } /// What every page's chrome needs. #[derive(Clone, Debug)] pub struct Shell { pub site: String, pub base_url: String, pub path: String, pub version: &'static str, } impl Shell { pub fn new(app: &Shared, path: &str) -> Shell { Shell { site: app.config.site.name.clone(), base_url: app.config.base_url().to_string(), path: path.to_string(), version: env!("CARGO_PKG_VERSION"), } } } /// The repository chrome: tabs and counts. #[derive(Clone, Debug)] pub struct RepoShell { pub owner: String, pub name: String, pub url: String, pub description: String, pub default_bookmark: String, pub visibility: String, pub tab: &'static str, pub clone_url: String, } impl RepoShell { pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell { RepoShell { owner: row.owner.clone(), name: row.name.clone(), url: format!("/{}/{}", row.owner, row.name), description: row.description.clone(), default_bookmark: row.default_bookmark.clone(), visibility: row.visibility.clone(), tab, clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name), } } } /// Render a template as an HTML response. pub struct Page(pub T); impl IntoResponse for Page { fn into_response(self) -> Response { match self.0.render() { Ok(s) => Html(s).into_response(), Err(e) => { tracing::error!("template: {e}"); (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response() } } } } #[derive(Template)] #[template(path = "error.html")] struct ErrorPage { shell: Shell, status: u16, title: String, detail: String, } /// A page-level failure, rendered inside the shell. #[derive(Debug)] pub struct Error { pub status: StatusCode, pub detail: String, shell: Option, } impl Error { pub fn not_found(shell: Shell) -> Error { Error { status: StatusCode::NOT_FOUND, detail: "There is nothing at this address.".into(), shell: Some(shell) } } pub fn bad(shell: Shell, detail: impl Into) -> Error { Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(shell) } } pub fn from_repo(shell: Shell, e: RepoError) -> Error { match e { RepoError::NotFound => Error::not_found(shell), RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(shell) }, other => Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(shell) }, } } pub fn from_db(shell: Shell, e: sqlx::Error) -> Error { Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(shell) } } } impl IntoResponse for Error { fn into_response(self) -> Response { let title = match self.status { StatusCode::NOT_FOUND => "Not found", StatusCode::BAD_REQUEST => "Bad request", _ => "Something went wrong", }; if self.status.is_server_error() { tracing::error!("{}", self.detail); } let shell = self.shell.unwrap_or(Shell { site: "Oxygenhub".into(), base_url: String::new(), path: String::new(), version: "" }); let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail }; match page.render() { Ok(s) => (self.status, Html(s)).into_response(), Err(_) => (self.status, title).into_response(), } } } async fn not_found(axum::extract::State(app): axum::extract::State, uri: axum::http::Uri) -> Response { Error::not_found(Shell::new(&app, uri.path())).into_response() } /// A raw file response with a safe content type (hub spec §15.2). pub fn raw(bytes: Vec, name: &str, inline_image: bool) -> Response { let mime = mime_of(name); let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" }; ( [ (header::CONTENT_TYPE, mime.to_string()), (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))), (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()), ], bytes, ) .into_response() } pub fn mime_of(name: &str) -> &'static str { match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() { Some("png") => "image/png", Some("jpg" | "jpeg") => "image/jpeg", Some("gif") => "image/gif", Some("webp") => "image/webp", Some("svg") => "image/svg+xml", Some("pdf") => "application/pdf", Some( "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh", ) => "text/plain; charset=utf-8", _ => "application/octet-stream", } } /// Resolve `{owner}/{name}` to its row, or 404. Private repositories are /// invisible until accounts exist (hub 0.2). pub async fn lookup(app: &Shared, shell: &Shell, owner: &str, name: &str) -> Result<(crate::repos::RepoName, db::repos::RepoRow), Error> { let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?; let row = db::repos::get(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))?; match row { Some(r) if r.visibility() == hub_api::Visibility::Public => Ok((repo, r)), _ => Err(Error::not_found(shell.clone())), } }