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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use std::time::Duration;
use url::{ParseError, Url};
mod error;
mod resolvers;
mod services;
use services::{which_service, SERVICES};
#[cfg(test)]
mod tests;
pub type Error = error::Error;
pub type Result<T> = std::result::Result<T, Error>;
use futures::future::{ready, TryFutureExt};
pub fn is_shortened(url: &str) -> bool {
SERVICES.iter().any(|x| url.contains(x))
}
#[cfg(feature = "blocking")]
pub fn unshorten_blocking(url: &str, timeout: Option<Duration>) -> Result<String> {
let rt = tokio::runtime::Runtime::new()?;
rt.block_on(unshorten(url, timeout))
}
pub async fn unshorten(url: &str, timeout: Option<Duration>) -> Result<String> {
ready(validate(url).ok_or(Error::NoString))
.and_then(|validated_url| async move {
let service = which_service(&validated_url).ok_or(Error::NoString)?;
match service {
"adf.ly" | "atominik.com" | "fumacrom.com" | "intamema.com" | "j.gs" | "q.gs" => {
resolvers::adfly::unshort(&validated_url, timeout).await
}
"gns.io" | "ity.im" | "ldn.im" | "nowlinks.net" | "rlu.ru" | "tinyurl.com"
| "tr.im" | "u.to" | "vzturl.com" => {
resolvers::redirect::unshort(&validated_url, timeout).await
}
"cutt.us" | "soo.gd" => resolvers::refresh::unshort(&validated_url, timeout).await,
"adfoc.us" => resolvers::adfocus::unshort(&validated_url, timeout).await,
"shorturl.at" => resolvers::shorturl::unshort(&validated_url, timeout).await,
"surl.li" => resolvers::surlli::unshort(&validated_url, timeout).await,
_ => resolvers::generic::unshort(&validated_url, timeout).await,
}
})
.await
}
fn validate(u: &str) -> Option<String> {
let parts = match Url::parse(u) {
Ok(p) => p,
Err(e) => match e {
ParseError::RelativeUrlWithoutBase => {
let new_url = format!("https://{}", u);
match Url::parse(&new_url) {
Ok(p) => p,
Err(_) => return None,
}
}
_ => return None,
},
};
parts
.domain()
.and_then(|domain| is_shortened(domain).then(|| parts.as_str().into()))
}