blob: 3d5a926db1dc56e3d53e076f83768b7ba5121469 (
plain) (
blame)
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
|
use anyhow::{Context, Result};
use reqwest::{Client, cookie::Jar};
use std::{collections::HashMap, fs, path::PathBuf, sync::Arc};
/// Reads the cookies.json file and builds an authenticated reqwest client.
pub fn build_authenticated_client(cookies_path: &PathBuf) -> Result<Client> {
// Read the JSON file.
println!("Reading cookies from {cookies_path:?}...");
let cookies_content = fs::read(cookies_path)
.with_context(|| format!("Failed to read cookies file from {cookies_path:?}."))?;
// Parse the JSON into a Rust HashMap.
let cookies_map: HashMap<String, String> = serde_json::from_slice(&cookies_content)
.context("Failed to parse cookies file. Ensure it is a flat key-value JSON object.")?;
// Create a Cookie Jar.
let jar = Arc::new(Jar::default());
// `reqwest` needs a URL to associate the cookies with.
let url = "https://learning.oreilly.com".parse::<reqwest::Url>()?;
for (key, value) in cookies_map {
// `reqwest` expects cookies in the standard "key=value" string format.
let cookie_str = format!("{}={}", key, value);
jar.add_cookie_str(&cookie_str, &url);
}
// Build the client with the cookie provider and a standard User-Agent.
let client = Client::builder()
.cookie_provider(jar)
.user_agent(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:147.0) Gecko/20100101 Firefox/147.0",
)
.build()
.context("Failed to build the HTTP client")?;
Ok(client)
}
|