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
use http::HeaderMap;

const X_CLIENT_PROFILE: &str = "x-client-profile";

/// This is the default user agent profile used by the library.
/// It can be overridden by setting the `x-client-profile` header.
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum AgentProfile {
    Chrome,
    Firefox,
    Safari,
    Edge,
    OkHttp,
}

impl AgentProfile {
    /// To header (key, value)
    pub fn to_header(&self) -> (&'static str, String) {
        (X_CLIENT_PROFILE, self.to_string())
    }
}

/// Default to Chrome
impl Default for AgentProfile {
    fn default() -> Self {
        AgentProfile::Chrome
    }
}

/// Convert the profile to a string
impl ToString for AgentProfile {
    fn to_string(&self) -> String {
        match self {
            AgentProfile::Chrome => "chrome",
            AgentProfile::Firefox => "firefox",
            AgentProfile::Safari => "safari",
            AgentProfile::Edge => "edge",
            AgentProfile::OkHttp => "okhttp",
        }
        .to_owned()
    }
}

/// Convert a string to a profile
impl From<&str> for AgentProfile {
    fn from(s: &str) -> Self {
        match s {
            "chrome" => AgentProfile::Chrome,
            "firefox" => AgentProfile::Firefox,
            "safari" => AgentProfile::Safari,
            "edge" => AgentProfile::Edge,
            "okhttp" => AgentProfile::OkHttp,
            _ => AgentProfile::Chrome,
        }
    }
}

/// Convert HeaderMap to profile, will remove the header
impl From<&mut HeaderMap> for AgentProfile {
    fn from(headers: &mut HeaderMap) -> Self {
        let profile = match headers.get(X_CLIENT_PROFILE) {
            Some(profile) => match profile.to_str() {
                Ok(v) => Self::from(v),
                Err(_) => Self::Chrome,
            },
            None => Self::Chrome,
        };
        headers.remove(X_CLIENT_PROFILE);
        profile
    }
}