fedora/
anonymous.rs

1//! This module contains an implementation for building anonymous [`Session`]s.
2
3use std::time::Duration;
4
5use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, USER_AGENT};
6use reqwest::redirect::Policy;
7use reqwest::Client;
8
9use crate::session::Session;
10use crate::{DEFAULT_TIMEOUT, FEDORA_USER_AGENT};
11
12/// This type encapsulates the (optional) arguments that are required for building an anonymous
13/// session.
14#[derive(Debug, Default)]
15pub struct AnonymousSessionBuilder<'a> {
16    /// optional override of the default timeout duration
17    timeout: Option<Duration>,
18    /// optional override of the default User-Agent header
19    user_agent: Option<&'a str>,
20}
21
22impl<'a> AnonymousSessionBuilder<'a> {
23    /// This method constructs a new [`AnonymousSessionBuilder`] instance.
24    pub fn new() -> Self {
25        AnonymousSessionBuilder {
26            timeout: None,
27            user_agent: None,
28        }
29    }
30
31    /// Override the default request timeout duration.
32    #[must_use]
33    pub fn timeout(mut self, timeout: Duration) -> Self {
34        self.timeout = Some(timeout);
35        self
36    }
37
38    /// Override the default User-Agent header.
39    #[must_use]
40    pub fn user_agent(mut self, user_agent: &'a str) -> Self {
41        self.user_agent = Some(user_agent);
42        self
43    }
44
45    /// This method consumes the [`AnonymousSessionBuilder`] and returns a [`Session`] with
46    /// custom timeout and User-Agent header settings.
47    ///
48    /// Note: This method will panic if the network stack cannot be initialized.
49    pub fn build(self) -> Session {
50        let timeout = match self.timeout {
51            Some(timeout) => timeout,
52            None => DEFAULT_TIMEOUT,
53        };
54
55        let user_agent = match self.user_agent {
56            Some(user_agent) => user_agent,
57            None => FEDORA_USER_AGENT,
58        };
59
60        // set default headers for our requests
61        // - User Agent
62        // - Accept: application/json
63        let mut headers = HeaderMap::new();
64
65        headers.insert(
66            USER_AGENT,
67            HeaderValue::from_str(user_agent).expect("Failed to parse hardcoded HTTP headers."),
68        );
69        headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
70
71        // construct reqwest session with:
72        // - custom default headers
73        // - no-redirects policy
74        let client = Client::builder()
75            .default_headers(headers)
76            .cookie_store(true)
77            .timeout(timeout)
78            .redirect(Policy::none())
79            .build()
80            .expect("Failed to initialize the network stack.");
81
82        Session { client }
83    }
84}