Skip to main content

fritz_core/
fault.rs

1//! The faults of a FRITZ!Box that are about the user, not the action: a
2//! missing right, and the second factor some actions need.
3//!
4//! The device asks for a second factor (UPnP error 866) before it runs some
5//! actions that change settings. It is confirmed on the device, by a button
6//! or a phone code, never by this crate. While a confirmation runs, others
7//! are busy (868), and after failed ones the device blocks them for up to an
8//! hour (867).
9
10use std::fmt;
11use std::time::Duration;
12
13use serde::Serialize;
14
15/// A fault of the device about the user.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
17#[serde(rename_all = "snake_case")]
18pub enum Fault {
19    /// The user lacks the right for the action (606).
20    Denied,
21    /// The action needs a second factor (866).
22    ConfirmationRequired,
23    /// Confirmations are blocked after failed ones (867).
24    Blocked,
25    /// Another confirmation is running (868).
26    Busy,
27}
28
29impl Fault {
30    /// The fault a UPnP error code stands for, if any.
31    pub fn from_code(code: u16) -> Option<Self> {
32        match code {
33            606 => Some(Self::Denied),
34            866 => Some(Self::ConfirmationRequired),
35            867 => Some(Self::Blocked),
36            868 => Some(Self::Busy),
37            _ => None,
38        }
39    }
40
41    /// The fault of an error, if the device answered with one.
42    pub fn of(error: &tr064::Error) -> Option<Self> {
43        error.upnp_code().and_then(Self::from_code)
44    }
45
46    /// The UPnP error code.
47    pub fn code(self) -> u16 {
48        match self {
49            Self::Denied => 606,
50            Self::ConfirmationRequired => 866,
51            Self::Blocked => 867,
52            Self::Busy => 868,
53        }
54    }
55
56    /// A name for machines, like `confirmation_required`.
57    pub fn status(self) -> &'static str {
58        match self {
59            Self::Denied => "denied",
60            Self::ConfirmationRequired => "confirmation_required",
61            Self::Blocked => "blocked",
62            Self::Busy => "busy",
63        }
64    }
65
66    /// The longest time to wait before trying again, if waiting helps.
67    pub fn retry_after(self) -> Option<Duration> {
68        match self {
69            Self::Blocked => Some(Duration::from_hours(1)),
70            Self::Busy => Some(Duration::from_mins(2)),
71            Self::Denied | Self::ConfirmationRequired => None,
72        }
73    }
74
75    /// Whether the device holds back all confirmations for a while, so that
76    /// the next calls fail the same way.
77    pub fn is_temporary(self) -> bool {
78        self.retry_after().is_some()
79    }
80}
81
82impl fmt::Display for Fault {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        let text = match self {
85            Self::Denied => "the user lacks the right for this action",
86            Self::ConfirmationRequired => {
87                "the device wants this action confirmed with a second factor, \
88                 which fritz never does"
89            }
90            Self::Blocked => {
91                "the device blocks confirmations after failed ones; \
92                 try again in up to an hour"
93            }
94            Self::Busy => {
95                "the device is busy with another confirmation; \
96                 try again in a few minutes"
97            }
98        };
99        write!(f, "{text} (UPnP error {})", self.code())
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    const ALL: [Fault; 4] = [
108        Fault::Denied,
109        Fault::ConfirmationRequired,
110        Fault::Blocked,
111        Fault::Busy,
112    ];
113
114    #[test]
115    fn maps_the_codes() {
116        for fault in ALL {
117            assert_eq!(Fault::from_code(fault.code()), Some(fault));
118        }
119        assert_eq!(Fault::from_code(713), None);
120        assert_eq!(Fault::from_code(401), None);
121    }
122
123    #[test]
124    fn finds_the_fault_of_an_error() {
125        let error = tr064::Error::Upnp {
126            code: 866,
127            description: "second factor authentication required".to_owned(),
128        };
129        assert_eq!(Fault::of(&error), Some(Fault::ConfirmationRequired));
130        assert_eq!(Fault::of(&tr064::Error::AuthenticationFailed), None);
131    }
132
133    #[test]
134    fn describes_the_faults() {
135        let names: Vec<_> = ALL.iter().map(|f| f.status()).collect();
136        assert_eq!(
137            names,
138            ["denied", "confirmation_required", "blocked", "busy"]
139        );
140        for fault in ALL {
141            assert_eq!(
142                serde_json::to_value(fault).unwrap(),
143                serde_json::json!(fault.status())
144            );
145            let text = fault.to_string();
146            assert!(text.ends_with(&format!("(UPnP error {})", fault.code())));
147        }
148        assert!(Fault::ConfirmationRequired.to_string().contains("never"));
149    }
150
151    #[test]
152    fn says_when_to_try_again() {
153        let waits: Vec<_> = ALL.iter().map(|f| f.retry_after()).collect();
154        assert_eq!(
155            waits,
156            [
157                None,
158                None,
159                Some(Duration::from_hours(1)),
160                Some(Duration::from_mins(2))
161            ]
162        );
163        assert!(Fault::Blocked.is_temporary());
164        assert!(!Fault::Denied.is_temporary());
165    }
166}