-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcid_contact.rs
More file actions
75 lines (62 loc) · 1.98 KB
/
cid_contact.rs
File metadata and controls
75 lines (62 loc) · 1.98 KB
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
72
73
74
75
use std::fmt;
use color_eyre::Result;
use reqwest::Client;
use tracing::{debug, info};
pub enum CidContactError {
InvalidResponse,
NoData,
}
impl fmt::Display for CidContactError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
CidContactError::InvalidResponse => "InvalidResponse",
CidContactError::NoData => "NoData",
};
write!(f, "{s}")
}
}
pub async fn get_contact(peer_id: &str) -> Result<serde_json::Value, CidContactError> {
let client = Client::new();
let url = format!("https://cid.contact/providers/{peer_id}");
debug!("cid contact url: {:?}", url);
let res = client
.get(&url)
.header("Accept", "application/json")
.header("User-Agent", "url-finder/0.1.0")
.send()
.await
.map_err(|_| CidContactError::InvalidResponse)?;
debug!("cid contact status: {:?}", res.status());
if !res.status().is_success() {
info!(
"cid contact returned non-success status: {:?}",
res.status()
);
return Err(CidContactError::NoData);
}
let json = res.json::<serde_json::Value>().await.map_err(|e| {
debug!("Failed to parse cid contact response: {:?}", e);
CidContactError::NoData
})?;
debug!("cid contact res: {:?}", json);
Ok(json)
}
pub fn get_all_addresses_from_response(json: serde_json::Value) -> Vec<String> {
let mut addresses = vec![];
if let Some(e_providers) = json
.get("ExtendedProviders")
.and_then(|ep| ep.get("Providers"))
.and_then(|p| p.as_array())
{
e_providers
.iter()
.filter_map(|provider| provider.get("Addrs"))
.filter_map(|addrs| addrs.as_array())
.flat_map(|addrs_arr| addrs_arr.iter())
.filter_map(|addr| addr.as_str())
.for_each(|addr| {
addresses.push(addr.to_string());
});
}
addresses
}