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
// User-facing output things

use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ConsoleOutputMode {
    Text,
    JSON,
}
impl Default for ConsoleOutputMode {
    fn default() -> Self {
        ConsoleOutputMode::Text
    }
}

impl FromStr for ConsoleOutputMode {
    type Err = &'static str;
    /// This can be safely unwrap'd because it'll always return a default
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "json" => Ok(ConsoleOutputMode::JSON),
            "text" => Ok(ConsoleOutputMode::Text),
            _ => {
                eprintln!(
                    "Supplied output mode ({:?}) was invalid, defaulting to text",
                    s
                );
                Ok(ConsoleOutputMode::Text)
            }
        }
    }
}

/// This will take any string, if it's 'text' or 'json' then you'll get
/// what you asked for, else you'll get a text version.
///
/// ```
/// use kanidm_proto::messages::ConsoleOutputMode;
/// let bork = "text";
/// let com: ConsoleOutputMode = bork.into();
/// matches!(ConsoleOutputMode::Text, com);
/// ```
impl From<&str> for ConsoleOutputMode {
    fn from(input: &str) -> Self {
        match ConsoleOutputMode::from_str(input) {
            Ok(val) => val,
            Err(_) => Self::Text,
        }
    }
}

/// This will take any string, if it's 'text' or 'json' then you'll get
/// what you asked for, else you'll get a text version.
///
/// ```
/// use kanidm_proto::messages::ConsoleOutputMode;
/// let bork = String::from("cr4bz");
/// let com: ConsoleOutputMode = bork.into();
/// matches!(ConsoleOutputMode::Text, com);
/// ```
impl From<String> for ConsoleOutputMode {
    fn from(input: String) -> Self {
        match ConsoleOutputMode::from_str(input.as_str()) {
            Ok(val) => val,
            Err(_) => Self::Text,
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MessageStatus {
    Failure,
    Success,
}

impl fmt::Display for MessageStatus {
    fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> {
        match *self {
            MessageStatus::Failure => f.write_str("failure"),
            MessageStatus::Success => f.write_str("success"),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AccountChangeMessage {
    #[serde(skip_serializing)]
    pub output_mode: ConsoleOutputMode,
    pub action: String,
    pub result: String,
    pub status: MessageStatus,
    pub src_user: String,
    pub dest_user: String,
}

impl Default for AccountChangeMessage {
    fn default() -> Self {
        AccountChangeMessage {
            output_mode: ConsoleOutputMode::Text,
            action: String::from(""),
            result: String::from(""),
            status: MessageStatus::Success,
            src_user: String::from(""),
            dest_user: String::from(""),
        }
    }
}

/// This outputs in either JSON or Text depending on the output_mode setting
impl fmt::Display for AccountChangeMessage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.output_mode {
            ConsoleOutputMode::JSON => write!(
                f,
                "{}",
                serde_json::to_string(self).unwrap_or(format!("{:?}", self)) // if it fails to JSON serialize, just debug-dump it
            ),
            ConsoleOutputMode::Text => write!(
                f,
                "{} - {} for user {}: {}",
                self.status, self.action, self.dest_user, self.result,
            ),
        }
    }
}