bobashare_web/views/
display.rs

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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
//! Routes to display or download an upload in a browser

use anyhow::Context;
use askama::Template;
use axum::{
    body::Body,
    extract::{Path, Query, State},
    response::IntoResponse,
};
use bobashare::storage::{file::OpenUploadError, handle::UploadHandle};
use chrono::{DateTime, Duration, Utc};
use displaydoc::Display;
use hyper::{header, StatusCode};
use mime::Mime;
use serde::{Deserialize, Deserializer};
use syntect::{html::ClassedHTMLGenerator, util::LinesWithEndings};
use thiserror::Error;
use tokio::io::AsyncReadExt;
use tokio_util::io::ReaderStream;
use tracing::{event, instrument, Level};
use url::Url;

use super::{filters, prelude::*, render_template, ErrorResponse, ErrorTemplate, TemplateState};
use crate::{render_markdown_with_syntax_set, AppState, CLASS_STYLE};

/// Errors when trying to view/download an upload
#[derive(Debug, Error, Display)]
pub enum ViewUploadError {
    /// an upload at the specified id was not found
    NotFound,

    /// internal server error
    InternalServer(#[from] anyhow::Error),
}
impl From<OpenUploadError> for ViewUploadError {
    fn from(err: OpenUploadError) -> Self {
        match err {
            OpenUploadError::NotFound(_) => Self::NotFound,
            _ => Self::InternalServer(anyhow::Error::new(err).context("error opening upload")),
        }
    }
}

async fn open_upload<S: AsRef<str>>(
    state: &AppState,
    id: S,
) -> Result<UploadHandle, ViewUploadError> {
    let upload = state.backend.open_upload(id.as_ref(), false).await?;

    if upload.metadata.is_expired() {
        event!(Level::INFO, "upload is expired; it will be deleted");
        // don't upload.flush() since it's not open for writing -- it will fail
        state
            .backend
            .delete_upload(id.as_ref())
            .await
            .context("error deleting expired upload")?;
        return Err(ViewUploadError::NotFound);
    }

    Ok(upload)
}

#[derive(Template)]
#[template(path = "display.html.jinja")]
pub struct DisplayTemplate<'s> {
    pub state: TemplateState<'s>,
    pub id: String,
    pub filename: String,
    pub expiry_date: Option<DateTime<Utc>>,
    pub expiry_relative: Option<Duration>,
    pub size: u64,
    pub mimetype: Mime,
    pub contents: DisplayType,
    pub raw_url: Url,
    pub download_url: Url,
}
#[derive(Debug)]
pub enum DisplayType {
    Text {
        highlighted: String,
    },
    Markdown {
        highlighted: String,
        displayed: String,
    },
    Image,
    Video,
    Audio,
    Pdf,
    Other,
    TooLarge,
}

/// Maximum file size that will be rendered
const MAX_DISPLAY_SIZE: u64 = 1024 * 1024; // 1 MiB

/// Display an upload as HTML
#[instrument(skip(state))]
pub async fn display(
    State(state): State<&'static AppState>,
    Path(id): Path<String>,
) -> Result<impl IntoResponse, ErrorResponse> {
    let tmpl_state = TemplateState::from(state);
    let mut upload = open_upload(state, id).await.map_err(|e| match e {
        ViewUploadError::NotFound => ErrorTemplate {
            state: tmpl_state.clone(),
            code: StatusCode::NOT_FOUND,
            message: e.to_string(),
        },
        ViewUploadError::InternalServer(_) => ErrorTemplate {
            state: tmpl_state.clone(),
            code: StatusCode::INTERNAL_SERVER_ERROR,
            message: e.to_string(),
        },
    })?;
    let size = upload
        .file
        .metadata()
        .await
        .map_err(|e| ErrorTemplate {
            state: tmpl_state.clone(),
            code: StatusCode::INTERNAL_SERVER_ERROR,
            message: format!("error reading file size: {e}"),
        })?
        .len();

    let contents = {
        let mimetype = upload.metadata.mimetype.clone();
        match (mimetype.type_(), mimetype.subtype()) {
            (mime::TEXT, _) | (mime::APPLICATION, mime::JSON) => {
                if size > MAX_DISPLAY_SIZE {
                    DisplayType::TooLarge
                } else {
                    let extension = std::path::Path::new(&upload.metadata.filename)
                        .extension()
                        .and_then(|s| s.to_str())
                        .unwrap_or("");
                    let syntax = state
                        .syntax_set
                        .find_syntax_by_extension(extension)
                        .unwrap_or_else(|| state.syntax_set.find_syntax_plain_text());
                    // should be alright to assume that 1,048,576 fits in usize on relevant
                    // platforms
                    let mut contents = String::with_capacity(size as usize);
                    upload
                        .file
                        .read_to_string(&mut contents)
                        .await
                        .map_err(|e| ErrorTemplate {
                            state: tmpl_state.clone(),
                            code: StatusCode::INTERNAL_SERVER_ERROR,
                            message: format!("error reading file contents: {e}"),
                        })?;

                    event!(
                        Level::DEBUG,
                        "highlighting file with syntax {}",
                        syntax.name
                    );
                    let highlighted = {
                        let mut generator = ClassedHTMLGenerator::new_with_class_style(
                            syntax,
                            &state.syntax_set,
                            CLASS_STYLE,
                        );
                        for line in LinesWithEndings::from(&contents) {
                            generator
                                .parse_html_for_line_which_includes_newline(line)
                                .map_err(|e| ErrorTemplate {
                                    state: tmpl_state.clone(),
                                    code: StatusCode::INTERNAL_SERVER_ERROR,
                                    message: format!("error highlighting file contents: {e}"),
                                })?;
                        }
                        generator.finalize()
                    };

                    if extension.eq_ignore_ascii_case("md") {
                        let displayed = render_markdown_with_syntax_set(
                            &contents,
                            &state.syntax_set,
                        )
                        .map_err(|e| ErrorTemplate {
                            state: tmpl_state.clone(),
                            code: StatusCode::INTERNAL_SERVER_ERROR,
                            message: format!("error highlighting markdown fenced code block: {e}",),
                        })?;

                        DisplayType::Markdown {
                            highlighted,
                            displayed,
                        }
                    } else {
                        DisplayType::Text { highlighted }
                    }
                }
            }
            (mime::IMAGE, _) => DisplayType::Image,
            (mime::VIDEO, _) => DisplayType::Video,
            (mime::AUDIO, _) => DisplayType::Audio,
            (mime::APPLICATION, mime::PDF) => DisplayType::Pdf,
            (_, _) => DisplayType::Other,
        }
    };

    event!(Level::DEBUG, "rendering upload template");
    let raw_url = state.raw_url.join(&upload.metadata.id).unwrap();
    let mut download_url = raw_url.clone();
    download_url.set_query(Some("download"));
    render_template(DisplayTemplate {
        raw_url,
        download_url,
        id: upload.metadata.id,
        filename: upload.metadata.filename,
        expiry_date: upload.metadata.expiry_date,
        expiry_relative: upload.metadata.expiry_date.map(|e| e - Utc::now()),
        size,
        mimetype: upload.metadata.mimetype,
        contents,
        state: tmpl_state,
    })
}

fn string_is_true<'de, D>(_: D) -> Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    Ok(true)
}
#[derive(Debug, Deserialize)]
pub struct RawParams {
    #[serde(default, deserialize_with = "string_is_true")]
    download: bool,
}
/// Download the raw upload file
#[instrument(skip(state))]
pub async fn raw(
    State(state): State<&'static AppState>,
    Path(id): Path<String>,
    Query(RawParams { download }): Query<RawParams>,
) -> Result<impl IntoResponse, ErrorResponse> {
    let tmpl_state = TemplateState::from(state);
    let upload = open_upload(state, id).await.map_err(|e| match e {
        ViewUploadError::NotFound => ErrorTemplate {
            state: tmpl_state.clone(),
            code: StatusCode::NOT_FOUND,
            message: e.to_string(),
        },
        ViewUploadError::InternalServer(_) => ErrorTemplate {
            state: tmpl_state.clone(),
            code: StatusCode::INTERNAL_SERVER_ERROR,
            message: e.to_string(),
        },
    })?;

    let size = upload
        .file
        .metadata()
        .await
        .map_err(|e| ErrorTemplate {
            state: tmpl_state.clone(),
            code: StatusCode::INTERNAL_SERVER_ERROR,
            message: format!("error reading file size: {e}"),
        })?
        .len();
    event!(Level::DEBUG, size, "found size of upload file",);

    let body = Body::from_stream(ReaderStream::new(upload.file));

    event!(
        Level::INFO,
        "type" = %upload.metadata.mimetype,
        length = size,
        filename = upload.metadata.filename,
        "successfully streaming upload file to client"
    );
    Ok((
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, upload.metadata.mimetype.to_string()),
            (header::CONTENT_LENGTH, size.to_string()),
            (
                header::CONTENT_DISPOSITION,
                // if params.download {
                if download {
                    format!("attachment; filename=\"{}\"", upload.metadata.filename)
                } else {
                    format!("inline; filename=\"{}\"", upload.metadata.filename)
                },
            ),
        ],
        body,
    ))
}