hydrus_api/wrapper/
address.rs1use crate::api_core::common::OptionalStringNumber;
2use crate::api_core::endpoints::managing_cookies_and_http_headers::CookieBuilder;
3use crate::error::Result;
4use crate::Client;
5use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7pub struct Address {
8 client: Client,
9 domain: String,
10 path: String,
11}
12
13impl Address {
14 pub(crate) fn from_str(client: Client, domain: &str) -> Self {
15 let (domain, path) = domain.split_once("/").unwrap_or((domain, "/"));
16 Self {
17 client,
18 domain: domain.to_string(),
19 path: path.to_string(),
20 }
21 }
22
23 pub fn path(&self) -> &str {
25 &self.path
26 }
27
28 pub fn set_path<S: ToString>(&mut self, path: S) {
30 self.path = path.to_string();
31 }
32
33 pub async fn set_cookies(&self, cookies: Vec<DomainCookie>) -> Result<()> {
35 let cookies = cookies
36 .into_iter()
37 .map(|cookie| {
38 let mut builder = CookieBuilder::default()
39 .domain(&self.domain)
40 .path(&self.path)
41 .name(cookie.name)
42 .value(cookie.value);
43 if let Some(expires) = cookie.expires {
44 builder =
45 builder.expires(expires.duration_since(UNIX_EPOCH).unwrap().as_secs());
46 }
47 builder.build()
48 })
49 .collect();
50
51 self.client.set_cookies(cookies).await
52 }
53
54 pub async fn get_cookies(&self) -> Result<Vec<DomainCookie>> {
56 let response = self.client.get_cookies(&self.domain).await?;
57 let cookies = response
58 .cookies
59 .into_iter()
60 .map(DomainCookie::from)
61 .collect();
62
63 Ok(cookies)
64 }
65}
66
67#[derive(Clone, Debug)]
68pub struct DomainCookie {
69 pub name: String,
70 pub value: String,
71 pub expires: Option<SystemTime>,
72}
73
74impl DomainCookie {
75 pub fn new<S1: ToString, S2: ToString>(
77 name: S1,
78 value: S2,
79 expires: Option<SystemTime>,
80 ) -> Self {
81 Self {
82 name: name.to_string(),
83 value: value.to_string(),
84 expires,
85 }
86 }
87}
88
89impl From<[OptionalStringNumber; 5]> for DomainCookie {
90 fn from(cookie_entry: [OptionalStringNumber; 5]) -> Self {
91 let name = cookie_entry[0].string().unwrap_or("");
92 let value = cookie_entry[1].string().unwrap_or("");
93 let expires = cookie_entry[4]
94 .number()
95 .map(|n| UNIX_EPOCH + Duration::from_secs(n));
96
97 Self::new(name, value, expires)
98 }
99}