aboutsummaryrefslogtreecommitdiffstats
path: root/cms-backd/src/reply.rs
blob: 3634b101bd23aa04acf5c4bb61f5a50b8d6eab22 (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
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
// -*- coding: utf-8 -*-
//
// Simple CMS
//
// Copyright (C) 2011-2024 Michael Büsch <m@bues.ch>
//
// Licensed under the Apache License version 2.0
// or the MIT license, at your option.
// SPDX-License-Identifier: Apache-2.0 OR MIT

use anyhow as ah;
use std::fmt;

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum HttpStatus {
    Ok = 200,
    MovedPermanently = 301,
    BadRequest = 400,
    NotFound = 404,
    #[default]
    InternalServerError = 500,
}

impl From<HttpStatus> for u32 {
    fn from(status: HttpStatus) -> Self {
        status as Self
    }
}

impl fmt::Display for HttpStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let text = match self {
            Self::Ok => "Ok",
            Self::MovedPermanently => "Moved Permanently",
            Self::BadRequest => "Bad Request",
            Self::NotFound => "Not Found",
            Self::InternalServerError => "Internal Server Error",
        };
        write!(f, "{} {}", *self as u16, text)
    }
}

#[derive(Clone, Debug, Default)]
pub struct CmsReply {
    status: HttpStatus,
    body: Vec<u8>,
    mime: String,
    extra_http_headers: Vec<String>,
    extra_html_headers: Vec<String>,
    error_msg: String,
}

impl CmsReply {
    pub fn ok(body: Vec<u8>, mime: &str) -> Self {
        Self {
            status: HttpStatus::Ok,
            body,
            mime: mime.to_string(),
            ..Default::default()
        }
    }

    pub fn not_found(msg: &str) -> Self {
        Self {
            status: HttpStatus::NotFound,
            body: format!(
                r#"<p style="font-size: large;">{}: {}</p>"#,
                HttpStatus::NotFound,
                msg
            )
            .into_bytes(),
            mime: "text/html".to_string(),
            error_msg: msg.to_string(),
            ..Default::default()
        }
    }

    pub fn bad_request(msg: &str) -> Self {
        Self {
            status: HttpStatus::BadRequest,
            body: format!(
                r#"<p style="font-size: large;">{}: {}</p>"#,
                HttpStatus::BadRequest,
                msg
            )
            .into_bytes(),
            mime: "text/html".to_string(),
            error_msg: msg.to_string(),
            ..Default::default()
        }
    }

    pub fn redirect(location: &str) -> Self {
        let location = location.trim();
        Self {
            status: HttpStatus::MovedPermanently,
            body: format!(
                r#"<p style="font-size: large;">Moved permanently to <a href="{location}">{location}</a></p>"#
            )
            .into_bytes(),
            mime: "text/html".to_string(),
            extra_http_headers: vec![format!(r#"Location: {location}"#)],
            extra_html_headers: vec![format!(
                r#"<meta http-equiv="refresh" content="0; URL={location}" />"#
            )],
            ..Default::default()
        }
    }

    pub fn internal_error(msg: &str) -> Self {
        Self {
            status: HttpStatus::InternalServerError,
            body: format!(
                r#"<p style="font-size: large;">{}: {}</p>"#,
                HttpStatus::InternalServerError,
                msg
            )
            .into_bytes(),
            mime: "text/html".to_string(),
            error_msg: msg.to_string(),
            ..Default::default()
        }
    }

    pub fn status(&self) -> HttpStatus {
        self.status
    }

    pub fn set_status(&mut self, status: HttpStatus) {
        self.status = status;
    }

    pub fn mime(&self) -> &str {
        &self.mime
    }

    pub fn error_page_required(&self) -> bool {
        self.status() != HttpStatus::Ok
    }

    pub fn error_msg(&self) -> &str {
        &self.error_msg
    }

    pub fn extra_html_headers(&self) -> &[String] {
        &self.extra_html_headers
    }

    pub fn set_status_as_body(&mut self) {
        self.body = format!(r#"<p style="font-size: large;">{}</p>"#, self.status).into_bytes();
        self.mime = "text/html".to_string();
    }

    pub fn remove_error_msg(&mut self) {
        self.error_msg.clear();
    }

    pub fn add_http_header(&mut self, http_header: &str) {
        self.extra_http_headers.push(http_header.to_string());
    }
}

impl From<ah::Result<CmsReply>> for CmsReply {
    fn from(reply: ah::Result<CmsReply>) -> Self {
        match reply {
            Ok(reply) => reply,
            Err(err) => Self::internal_error(&format!("{err}")),
        }
    }
}

impl From<CmsReply> for cms_socket_back::Msg {
    fn from(reply: CmsReply) -> Self {
        cms_socket_back::Msg::Reply {
            status: reply.status.into(),
            body: reply.body,
            mime: reply.mime,
            extra_headers: reply.extra_http_headers,
        }
    }
}

// vim: ts=4 sw=4 expandtab
bues.ch cgit interface