aboutsummaryrefslogtreecommitdiff
path: root/server/src/helper/accept.rs
blob: 3ac53c840de6aa8a6ea17944bb4711c53c8c25db (plain)
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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2025 metamuffin <metamuffin.org>
*/
use rocket::{
    http::MediaType,
    outcome::Outcome,
    request::{self, FromRequest},
    Request,
};
use std::ops::Deref;

#[derive(Debug, Default)]
pub enum Accept {
    #[default]
    Other,
    Json,
    Image,
    Media,
    Html,
}
impl Accept {
    pub fn from_request_ut(request: &Request) -> Self {
        if let Some(a) = request.accept() {
            if a.preferred().exact_eq(&MediaType::JSON) {
                Accept::Json
            } else {
                Accept::Other
            }
        } else {
            Accept::Other
        }
    }
}

pub struct AcceptJson(bool);
impl Deref for AcceptJson {
    type Target = bool;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl<'r> FromRequest<'r> for AcceptJson {
    type Error = ();

    fn from_request<'life0, 'async_trait>(
        request: &'r Request<'life0>,
    ) -> ::core::pin::Pin<
        Box<
            dyn ::core::future::Future<Output = request::Outcome<Self, Self::Error>>
                + ::core::marker::Send
                + 'async_trait,
        >,
    >
    where
        'r: 'async_trait,
        'life0: 'async_trait,
        Self: 'async_trait,
    {
        Box::pin(async move {
            Outcome::Success(AcceptJson(matches!(
                Accept::from_request_ut(request),
                Accept::Json
            )))
        })
    }
}