|
| 1 | +use serde::{Deserialize, Serialize, Serializer}; |
| 2 | +use url::Url; |
| 3 | + |
| 4 | +use crate::{errors::AtomicResult, utils::random_string}; |
| 5 | + |
| 6 | +pub enum Routes { |
| 7 | + Agents, |
| 8 | + AllVersions, |
| 9 | + Collections, |
| 10 | + Commits, |
| 11 | + CommitsUnsigned, |
| 12 | + Endpoints, |
| 13 | + Import, |
| 14 | + Tpf, |
| 15 | + Version, |
| 16 | + Setup, |
| 17 | +} |
| 18 | + |
| 19 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| 20 | +/// Wrapper for URLs / subjects. |
| 21 | +/// Has a bunch of methods for finding or creating commonly used paths. |
| 22 | +pub struct AtomicUrl { |
| 23 | + url: Url, |
| 24 | +} |
| 25 | + |
| 26 | +impl AtomicUrl { |
| 27 | + pub fn new(url: Url) -> Self { |
| 28 | + Self { url } |
| 29 | + } |
| 30 | + |
| 31 | + pub fn as_str(&self) -> &str { |
| 32 | + self.url.as_str() |
| 33 | + } |
| 34 | + |
| 35 | + /// Returns the route to some common Endpoint |
| 36 | + pub fn set_route(&self, route: Routes) -> Self { |
| 37 | + let path = match route { |
| 38 | + Routes::AllVersions => "/all-versions".to_string(), |
| 39 | + Routes::Agents => "/agents".to_string(), |
| 40 | + Routes::Collections => "/collections".to_string(), |
| 41 | + Routes::Commits => "/commits".to_string(), |
| 42 | + Routes::CommitsUnsigned => "/commits-unsigned".to_string(), |
| 43 | + Routes::Endpoints => "/endpoints".to_string(), |
| 44 | + Routes::Import => "/import".to_string(), |
| 45 | + Routes::Tpf => "/tpf".to_string(), |
| 46 | + Routes::Version => "/version".to_string(), |
| 47 | + Routes::Setup => "/setup".to_string(), |
| 48 | + }; |
| 49 | + let mut new = self.url.clone(); |
| 50 | + new.set_path(&path); |
| 51 | + Self::new(new) |
| 52 | + } |
| 53 | + |
| 54 | + /// Returns a new URL generated from the provided path_shortname and a random string. |
| 55 | + /// ``` |
| 56 | + /// let url = atomic_lib::AtomicUrl::try_from("https://example.com").unwrap(); |
| 57 | + /// let generated = url.generate_random("my-type"); |
| 58 | + /// assert!(generated.to_string().starts_with("https://example.com/my-type/")); |
| 59 | + /// ``` |
| 60 | + pub fn generate_random(&self, path_shortname: &str) -> Self { |
| 61 | + let mut url = self.url.clone(); |
| 62 | + let path = format!("{path_shortname}/{}", random_string(10)); |
| 63 | + url.set_path(&path); |
| 64 | + Self { url } |
| 65 | + } |
| 66 | + |
| 67 | + /// Adds a sub-path to a URL. |
| 68 | + /// Adds a slash to the existing URL, followed by the passed path. |
| 69 | + /// |
| 70 | + /// ``` |
| 71 | + /// use atomic_lib::AtomicUrl; |
| 72 | + /// let start = "http://localhost"; |
| 73 | + /// let mut url = AtomicUrl::try_from(start).unwrap(); |
| 74 | + /// assert_eq!(url.to_string(), "http://localhost/"); |
| 75 | + /// url.append("/"); |
| 76 | + /// assert_eq!(url.to_string(), "http://localhost/"); |
| 77 | + /// url.append("someUrl/123"); |
| 78 | + /// assert_eq!(url.to_string(), "http://localhost/someUrl/123"); |
| 79 | + /// url.append("/345"); |
| 80 | + /// assert_eq!(url.to_string(), "http://localhost/someUrl/123/345"); |
| 81 | + /// ``` |
| 82 | + pub fn append(&mut self, path: &str) -> &Self { |
| 83 | + let mut new_path = self.url.path().to_string(); |
| 84 | + match (new_path.ends_with('/'), path.starts_with('/')) { |
| 85 | + (true, true) => { |
| 86 | + new_path.pop(); |
| 87 | + } |
| 88 | + (false, false) => new_path.push('/'), |
| 89 | + _other => {} |
| 90 | + }; |
| 91 | + |
| 92 | + // Remove first slash if it exists |
| 93 | + if new_path.starts_with('/') { |
| 94 | + new_path.remove(0); |
| 95 | + } |
| 96 | + |
| 97 | + new_path.push_str(path); |
| 98 | + |
| 99 | + self.url.set_path(&new_path); |
| 100 | + self |
| 101 | + } |
| 102 | + |
| 103 | + /// Sets the subdomain of the URL. |
| 104 | + /// Removes an existing subdomain if the subdomain is None |
| 105 | + pub fn set_subdomain(&mut self, subdomain: Option<&str>) -> AtomicResult<&Self> { |
| 106 | + let mut host = self.url.host_str().unwrap().to_string(); |
| 107 | + if let Some(subdomain) = subdomain { |
| 108 | + host = format!("{}.{}", subdomain, host); |
| 109 | + } |
| 110 | + self.url.set_host(Some(host.as_str()))?; |
| 111 | + Ok(self) |
| 112 | + } |
| 113 | + |
| 114 | + pub fn set_path(&mut self, path: &str) -> &Self { |
| 115 | + self.url.set_path(path); |
| 116 | + self |
| 117 | + } |
| 118 | + |
| 119 | + pub fn subdomain(&self) -> Option<String> { |
| 120 | + let url = self.url.clone(); |
| 121 | + let host = url.host_str().unwrap(); |
| 122 | + let parts: Vec<&str> = host.split('.').collect(); |
| 123 | + if parts.len() > 2 { |
| 124 | + Some(parts[0].to_string()) |
| 125 | + } else { |
| 126 | + None |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + /// Returns the inner {url::Url} struct that has a bunch of regular URL methods |
| 131 | + /// Useful if you need the host or something. |
| 132 | + pub fn url(&self) -> Url { |
| 133 | + self.url.clone() |
| 134 | + } |
| 135 | +} |
| 136 | + |
| 137 | +impl TryFrom<&str> for AtomicUrl { |
| 138 | + type Error = url::ParseError; |
| 139 | + |
| 140 | + fn try_from(value: &str) -> Result<Self, Self::Error> { |
| 141 | + let url = Url::parse(value)?; |
| 142 | + Ok(Self { url }) |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +impl Serialize for AtomicUrl { |
| 147 | + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 148 | + where |
| 149 | + S: Serializer, |
| 150 | + { |
| 151 | + serializer.serialize_str(self.url.as_str()) |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +impl<'de> Deserialize<'de> for AtomicUrl { |
| 156 | + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 157 | + where |
| 158 | + D: serde::Deserializer<'de>, |
| 159 | + { |
| 160 | + let s = String::deserialize(deserializer)?; |
| 161 | + let url = Url::parse(&s).map_err(serde::de::Error::custom)?; |
| 162 | + Ok(Self { url }) |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +impl std::fmt::Display for AtomicUrl { |
| 167 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 168 | + write!(f, "{}", self.url) |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +#[cfg(test)] |
| 173 | +mod test { |
| 174 | + use super::*; |
| 175 | + |
| 176 | + #[test] |
| 177 | + fn test_url() { |
| 178 | + let _should_fail = AtomicUrl::try_from("nonsense").unwrap_err(); |
| 179 | + let _should_succeed = AtomicUrl::try_from("http://localhost/someUrl").unwrap(); |
| 180 | + } |
| 181 | + |
| 182 | + #[test] |
| 183 | + fn subdomain() { |
| 184 | + let sub = "http://test.example.com"; |
| 185 | + assert_eq!( |
| 186 | + AtomicUrl::try_from(sub).unwrap().subdomain(), |
| 187 | + Some("test".to_string()) |
| 188 | + ); |
| 189 | + let mut no_sub = AtomicUrl::try_from("http://example.com").unwrap(); |
| 190 | + assert_eq!(no_sub.subdomain(), None); |
| 191 | + |
| 192 | + let to_sub = no_sub.set_subdomain(Some("mysub")).unwrap(); |
| 193 | + assert_eq!(to_sub.subdomain(), Some("mysub".to_string())); |
| 194 | + } |
| 195 | +} |
0 commit comments