OXYGENHUB
# 99ca93d60bca oxygenhub / crates / hub / src / web / mod.rs
8.0 KiB · Rust · last changed Milestone 0.1: browse 1 month ago source blame history raw
1
//! Pages (hub spec §6): the router, the shell every template extends, the
2
//! error page, and askama filters. Handlers are thin: they resolve names,
3
//! call the view layer under the repository lock, and render.
4
5
pub mod filters;
6
mod history;
7
mod home;
8
mod refs;
9
mod repo;
10
mod statics;
11
12
use crate::repos::RepoError;
13
use crate::{db, Shared};
14
use askama::Template;
15
use axum::extract::DefaultBodyLimit;
16
use axum::http::{header, StatusCode};
17
use axum::response::{Html, IntoResponse, Response};
18
use axum::routing::{any, get};
19
use axum::Router;
20
use tower_http::compression::CompressionLayer;
21
use tower_http::trace::TraceLayer;
22
23
pub fn router(app: Shared) -> Router {
24
    let push_limit = app.config.limits.push_body_limit.0 as usize;
25
    Router::new()
26
        .route("/", get(home::index))
27
        .route("/explore", get(home::explore))
28
        .route("/health", get(home::health))
29
        .route("/.well-known/oxyhub-key", get(home::hub_key))
30
        .route("/style.css", get(statics::style))
31
        .route("/favicon.svg", get(statics::favicon))
32
        .route("/favicon.ico", get(statics::favicon))
33
        .route("/static/{*path}", get(statics::asset))
34
        .nest("/api/v1", crate::api::router())
35
        .route("/{owner}", get(home::owner))
36
        .route("/{owner}/{name}", get(repo::overview))
37
        .route("/{owner}/{name}/tree/{r}", get(repo::tree_root))
38
        .route("/{owner}/{name}/tree/{r}/{*path}", get(repo::tree))
39
        .route("/{owner}/{name}/file/{r}/{*path}", get(repo::file))
40
        .route("/{owner}/{name}/last/{r}", get(repo::last_changes))
41
        .route("/{owner}/{name}/changes/{r}", get(history::history))
42
        .route("/{owner}/{name}/change/{hash}", get(history::change))
43
        .route("/{owner}/{name}/compare/{spec}", get(history::compare))
44
        .route("/{owner}/{name}/bookmarks", get(refs::bookmarks))
45
        .route("/{owner}/{name}/tags", get(refs::tags))
46
        .route("/{owner}/{name}/conflicts", get(refs::conflicts))
47
        .route("/{owner}/{name}/trust", get(refs::trust))
48
        .route("/{owner}/{name}/pushes", get(refs::pushes))
49
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
50
        .fallback(not_found)
51
        .layer(CompressionLayer::new())
52
        .layer(TraceLayer::new_for_http())
53
        .with_state(app)
54
}
55
56
/// What every page's chrome needs.
57
#[derive(Clone, Debug)]
58
pub struct Shell {
59
    pub site: String,
60
    pub base_url: String,
61
    pub path: String,
62
    pub version: &'static str,
63
}
64
65
impl Shell {
66
    pub fn new(app: &Shared, path: &str) -> Shell {
67
        Shell {
68
            site: app.config.site.name.clone(),
69
            base_url: app.config.base_url().to_string(),
70
            path: path.to_string(),
71
            version: env!("CARGO_PKG_VERSION"),
72
        }
73
    }
74
}
75
76
/// The repository chrome: tabs and counts.
77
#[derive(Clone, Debug)]
78
pub struct RepoShell {
79
    pub owner: String,
80
    pub name: String,
81
    pub url: String,
82
    pub description: String,
83
    pub default_bookmark: String,
84
    pub visibility: String,
85
    pub tab: &'static str,
86
    pub clone_url: String,
87
}
88
89
impl RepoShell {
90
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
91
        RepoShell {
92
            owner: row.owner.clone(),
93
            name: row.name.clone(),
94
            url: format!("/{}/{}", row.owner, row.name),
95
            description: row.description.clone(),
96
            default_bookmark: row.default_bookmark.clone(),
97
            visibility: row.visibility.clone(),
98
            tab,
99
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
100
        }
101
    }
102
}
103
104
/// Render a template as an HTML response.
105
pub struct Page<T: Template>(pub T);
106
107
impl<T: Template> IntoResponse for Page<T> {
108
    fn into_response(self) -> Response {
109
        match self.0.render() {
110
            Ok(s) => Html(s).into_response(),
111
            Err(e) => {
112
                tracing::error!("template: {e}");
113
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
114
            }
115
        }
116
    }
117
}
118
119
#[derive(Template)]
120
#[template(path = "error.html")]
121
struct ErrorPage {
122
    shell: Shell,
123
    status: u16,
124
    title: String,
125
    detail: String,
126
}
127
128
/// A page-level failure, rendered inside the shell.
129
#[derive(Debug)]
130
pub struct Error {
131
    pub status: StatusCode,
132
    pub detail: String,
133
    shell: Option<Shell>,
134
}
135
136
impl Error {
137
    pub fn not_found(shell: Shell) -> Error {
138
        Error { status: StatusCode::NOT_FOUND, detail: "There is nothing at this address.".into(), shell: Some(shell) }
139
    }
140
141
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
142
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(shell) }
143
    }
144
145
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
146
        match e {
147
            RepoError::NotFound => Error::not_found(shell),
148
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(shell) },
149
            other => Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(shell) },
150
        }
151
    }
152
153
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
154
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(shell) }
155
    }
156
}
157
158
impl IntoResponse for Error {
159
    fn into_response(self) -> Response {
160
        let title = match self.status {
161
            StatusCode::NOT_FOUND => "Not found",
162
            StatusCode::BAD_REQUEST => "Bad request",
163
            _ => "Something went wrong",
164
        };
165
        if self.status.is_server_error() {
166
            tracing::error!("{}", self.detail);
167
        }
168
        let shell = self.shell.unwrap_or(Shell { site: "Oxygenhub".into(), base_url: String::new(), path: String::new(), version: "" });
169
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
170
        match page.render() {
171
            Ok(s) => (self.status, Html(s)).into_response(),
172
            Err(_) => (self.status, title).into_response(),
173
        }
174
    }
175
}
176
177
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, uri: axum::http::Uri) -> Response {
178
    Error::not_found(Shell::new(&app, uri.path())).into_response()
179
}
180
181
/// A raw file response with a safe content type (hub spec §15.2).
182
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
183
    let mime = mime_of(name);
184
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
185
    (
186
        [
187
            (header::CONTENT_TYPE, mime.to_string()),
188
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
189
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
190
        ],
191
        bytes,
192
    )
193
        .into_response()
194
}
195
196
pub fn mime_of(name: &str) -> &'static str {
197
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
198
        Some("png") => "image/png",
199
        Some("jpg" | "jpeg") => "image/jpeg",
200
        Some("gif") => "image/gif",
201
        Some("webp") => "image/webp",
202
        Some("svg") => "image/svg+xml",
203
        Some("pdf") => "application/pdf",
204
        Some(
205
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
206
        ) => "text/plain; charset=utf-8",
207
        _ => "application/octet-stream",
208
    }
209
}
210
211
/// Resolve `{owner}/{name}` to its row, or 404. Private repositories are
212
/// invisible until accounts exist (hub 0.2).
213
pub async fn lookup(app: &Shared, shell: &Shell, owner: &str, name: &str) -> Result<(crate::repos::RepoName, db::repos::RepoRow), Error> {
214
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
215
    let row = db::repos::get(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))?;
216
    match row {
217
        Some(r) if r.visibility() == hub_api::Visibility::Public => Ok((repo, r)),
218
        _ => Err(Error::not_found(shell.clone())),
219
    }
220
}