about summary refs log tree commit diff stats
path: root/src/web/mod.rs
blob: 0f9835a049c5201461cc8daf8ca9387a2c128c9f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Back - An extremely simple git bug visualization system. Inspired by TVL's
// panettone.
//
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This file is part of Back.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/agpl.txt>.

use std::{cell::OnceCell, convert::Infallible, net::SocketAddr, path::PathBuf, sync::Arc};

use bytes::Bytes;
use git_bug::{
    entities::issue::{Issue, data::status::Status, query::MatchKeyValue},
    query::{Matcher, ParseMode, Query},
    replica::entity::{id::prefix::IdPrefix, snapshot::Snapshot},
};
use http_body_util::combinators::BoxBody;
use hyper::{Method, Request, Response, StatusCode, server::conn::http1, service::service_fn};
use hyper_util::rt::TokioIo;
use log::{error, info, warn};
use responses::{html_response, html_response_status, html_response_status_content_type, redirect};
use tokio::net::TcpListener;
use url::Url;

use crate::{config::BackConfig, error};

mod generate;
mod responses;

#[allow(clippy::unused_async, clippy::too_many_lines)]
async fn match_uri(
    config: Arc<BackConfig>,
    req: Request<hyper::body::Incoming>,
) -> Result<Response<BoxBody<Bytes, Infallible>>, hyper::Error> {
    if req.method() != Method::GET {
        return Ok(html_response_status(
            "Only get requests are supported",
            StatusCode::NOT_ACCEPTABLE,
        ));
    }

    let output = || -> Result<Response<BoxBody<Bytes, Infallible>>, error::Error> {
        match req.uri().path().trim_matches('/') {
            "" => Ok(html_response(generate::repos(&config)?)),

            "style.css" => Ok(html_response_status_content_type(
                include_str!("../../assets/style.css"),
                StatusCode::OK,
                "text/css",
            )),
            "search.png" => Ok(html_response_status_content_type(
                &include_bytes!("../../assets/search.png")[..],
                StatusCode::OK,
                "image/png",
            )),

            path if path.ends_with("/issues") => {
                let repo_path =
                    PathBuf::from(path.strip_suffix("/issues").expect("This suffix exists"));

                let replica = config
                    .repositories()?
                    .get(&repo_path)?
                    .open(&config.scan_path)?;

                let query = {
                    // HACK(@bpeetz): We cannot use the uri directly, because that would require us
                    // to parse the query string. As such, we need to turn into into a url::Url,
                    // which provides this. Unfortunately, this re-parsing is the “officially”
                    // sanctioned way of doing this. <2025-05-28>
                    let url: Url = format!("https://{}{}", config.root_url, req.uri())
                        .parse()
                        .expect("Was a url before");

                    let mut query = OnceCell::new();
                    for (name, value) in url.query_pairs() {
                        if name == "query" && query.get().is_none() {
                            let val =
                                Query::from_continuous_str(&replica, &value, ParseMode::Relaxed)
                                    .map_err(|err| error::Error::InvalidQuery {
                                        err,
                                        query: value.to_string(),
                                    })?;
                            query.set(val).expect("We checked for initialized");
                        } else {
                            warn!("Unknown url query key: {name}");
                        }
                    }

                    query.take()
                };

                if let Some(query) = query {
                    let issues = generate::issues(&config, &repo_path, &replica, &query)?;
                    Ok(html_response(issues))
                } else {
                    let query = Query::<Snapshot<Issue>>::from_matcher(Matcher::Match {
                        key_value: MatchKeyValue::Status(Status::Open),
                    });
                    Ok(redirect(&format!(
                        "/{}/issues/?query={}",
                        repo_path.display(),
                        query
                    )))
                }
            }
            path if path.ends_with("/issues/feed") => {
                let repo_path = PathBuf::from(
                    path.strip_suffix("/issues/feed")
                        .expect("This suffix exists")
                        .strip_prefix("/")
                        .expect("This also exists"),
                );

                let feed = generate::feed(&config, &repo_path)?;
                Ok(html_response_status_content_type(
                    feed,
                    StatusCode::OK,
                    "text/xml",
                ))
            }

            path if path.contains("/issue/") => {
                let (repo_path, prefix) = {
                    let split: Vec<&str> = path.split("/issue/").collect();

                    let prefix = IdPrefix::from_hex_bytes(split[1].as_bytes()).map_err(|err| {
                        error::Error::IssuesPrefixParse {
                            prefix: split[1].to_owned(),
                            error: err,
                        }
                    })?;

                    let repo_path = PathBuf::from(split[0]);

                    (repo_path, prefix)
                };
                Ok(html_response(generate::issue(&config, &repo_path, prefix)?))
            }

            other if config.repositories()?.get(&PathBuf::from(other)).is_ok() => {
                Ok(redirect(&format!("/{other}/issues/?query=status:open")))
            }
            other if config.repositories()?.get(&PathBuf::from(other)).is_err() => {
                Err(error::Error::NotGitBug {
                    path: PathBuf::from(other),
                })
            }

            other => Err(error::Error::NotFound(PathBuf::from(other))),
        }
    };
    match output() {
        Ok(response) => Ok(response),
        Err(err) => Ok(err.into_response()),
    }
}

pub(crate) async fn main(config: Arc<BackConfig>) -> Result<(), error::Error> {
    let addr: SocketAddr = ([127, 0, 0, 1], 8000).into();

    let listener = TcpListener::bind(addr)
        .await
        .map_err(|err| error::Error::TcpBind { addr, err })?;
    info!("Listening on http://{addr}");

    loop {
        let (stream, _) = listener
            .accept()
            .await
            .map_err(|err| error::Error::TcpAccept { err })?;
        let io = TokioIo::new(stream);

        let local_config = Arc::clone(&config);

        let service = service_fn(move |req| match_uri(Arc::clone(&local_config), req));

        tokio::task::spawn(async move {
            if let Err(err) = http1::Builder::new().serve_connection(io, service).await {
                error!("Error serving connection: {err:?}");
            }
        });
    }
}