Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
5.0 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

pub(in crate::server) mod error;

use crate::{
    byte_budget::BudgetedBytes,
    disposition, http_headers, range,
    server::format_policy::{extension_from_mime, image_extension_from_filename},
};
use axum::{
    body::Body,
    http::{HeaderValue, Method, StatusCode, header},
    response::Response,
};
use bytes::Bytes;
use std::borrow::Cow;

pub(in crate::server) fn retained_response_bytes(data: BudgetedBytes) -> Bytes {
    Bytes::from_owner(data)
}

pub(in crate::server) struct MediaResponse<'a> {
    pub(in crate::server) method: Method,
    pub(in crate::server) data: BudgetedBytes,
    pub(in crate::server) content_type: &'a str,
    pub(in crate::server) range_header: Option<&'a str>,
    pub(in crate::server) disposition: Option<HeaderValue>,
}

pub(in crate::server) fn media_response(response: MediaResponse<'_>) -> Response {
    let MediaResponse {
        method,
        data,
        content_type,
        range_header,
        disposition,
    } = response;
    let total_len = data.len();
    let byte_range = match range::parse_range(range_header, total_len) {
        range::RangeSelection::Full => None,
        range::RangeSelection::Partial(byte_range) => Some(byte_range),
        range::RangeSelection::Unsatisfiable => {
            let mut response = Response::new(Body::empty());
            *response.status_mut() = StatusCode::RANGE_NOT_SATISFIABLE;
            http_headers::add_unsatisfiable_headers(response.headers_mut(), total_len);
            return response;
        }
    };
    let retained = retained_response_bytes(data);
    let (status, body_bytes) = if let Some(r) = byte_range {
        (StatusCode::PARTIAL_CONTENT, retained.slice(r.start..=r.end))
    } else {
        (StatusCode::OK, retained)
    };
    let body_len = body_bytes.len();
    let body = if method == Method::HEAD {
        Body::empty()
    } else {
        Body::from(body_bytes)
    };
    media_body_response(
        body,
        status,
        total_len,
        content_type,
        byte_range,
        Some(body_len as u64),
        disposition,
    )
}

pub(in crate::server) struct GeneratedMediaResponse<'a> {
    pub(in crate::server) method: Method,
    pub(in crate::server) data: BudgetedBytes,
    pub(in crate::server) content_type: &'a str,
    pub(in crate::server) disposition: Option<HeaderValue>,
}

pub(in crate::server) fn generated_media_response(
    response: GeneratedMediaResponse<'_>,
) -> Response {
    let GeneratedMediaResponse {
        method,
        data,
        content_type,
        disposition,
    } = response;
    let total_len = data.len();
    let body = if method == Method::HEAD {
        Body::empty()
    } else {
        Body::from(retained_response_bytes(data))
    };
    let mut response = media_body_response(
        body,
        StatusCode::OK,
        total_len,
        content_type,
        None,
        Some(total_len as u64),
        disposition,
    );
    response.headers_mut().remove(header::ACCEPT_RANGES);
    response
}

pub(in crate::server) fn media_body_response(
    body: Body,
    status: StatusCode,
    total_len: usize,
    content_type: &str,
    byte_range: Option<range::ByteRange>,
    content_length: Option<u64>,
    disposition: Option<HeaderValue>,
) -> Response {
    let mut response = Response::new(body);
    *response.status_mut() = status;
    http_headers::add_media_headers(response.headers_mut(), total_len, content_type, byte_range);
    if let Some(length) = content_length {
        response
            .headers_mut()
            .insert(header::CONTENT_LENGTH, HeaderValue::from(length));
    }
    if let Some(value) = disposition {
        response
            .headers_mut()
            .insert(header::CONTENT_DISPOSITION, value);
    }
    response
}

pub(in crate::server) fn content_disposition_header(
    content_type: &str,
    requested_download: bool,
    filename: Option<&str>,
) -> HeaderValue {
    let decision = disposition::decide(content_type, requested_download);
    let filename = filename
        .map(|name| download_filename_for_content_type(name, content_type, requested_download));
    disposition::header(decision, filename.as_deref())
        .map(disposition::ContentDisposition::into_header_value)
        .unwrap_or_else(|_| decision.header_value())
}

fn download_filename_for_content_type<'a>(
    filename: &'a str,
    content_type: &str,
    requested_download: bool,
) -> Cow<'a, str> {
    if !requested_download || filename.is_empty() {
        return Cow::Borrowed(filename);
    }
    let Some(expected_ext) = extension_from_mime(content_type) else {
        return Cow::Borrowed(filename);
    };
    if image_extension_from_filename(filename) == Some(expected_ext) {
        return Cow::Borrowed(filename);
    }
    let ext = expected_ext.name();
    let Some((stem, _)) = filename.rsplit_once('.') else {
        return Cow::Owned(format!("{filename}.{ext}"));
    };
    if stem.is_empty() {
        Cow::Owned(format!("{filename}.{ext}"))
    } else {
        Cow::Owned(format!("{stem}.{ext}"))
    }
}