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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
//! # DuckDNS client library
//! Uses DuckDNS API to update your domain records with your IP address

#![doc(html_root_url = "https://docs.rs/duckdns/0.1.1")]
#![cfg_attr(all(feature = "cargo-clippy", feature = "pedantic"), warn(clippy_pedantic))]
#![cfg_attr(feature = "cargo-clippy", warn(use_self))]
#![deny(warnings, missing_debug_implementations)]

extern crate reqwest;

use std::net::IpAddr;

const DUCKDNS_URL: &str = "https://www.duckdns.org/update";

/// Configuration builder object.
#[derive(Debug)]
pub struct DuckDns {
    token: String,
    domains: Option<String>,
    ipv4: Option<String>,
    ipv6: Option<String>,
    verbose: bool,
    clear: bool,
}

impl DuckDns {
    /// Creates new instance of `DuckDns` updater with your private token.
    pub fn new<S: AsRef<str>>(token: S) -> Self {
        Self {
            token: token.as_ref().to_string(),
            domains: None,
            ipv4: None,
            ipv6: None,
            verbose: false,
            clear: false,
        }
    }

    /// Specifies which domain or list of domains to update
    /// (comma separated list in case of multiple domains)
    pub fn domains<S: AsRef<str>>(self, domains: S) -> Self {
        let domains = Some(domains.as_ref().to_string());
        Self { domains, ..self }
    }

    /// Specifies an explicit IPv4 address for the update.
    /// Without it DuckDNS service will use the source of your request for the update.
    pub fn ipv4<S: AsRef<str>>(self, ipv4: S) -> Self {
        let ipv4 = Some(ipv4.as_ref().to_string());
        Self { ipv4, ..self }
    }

    /// Specifies an explicit IPv6 address for the update.
    pub fn ipv6<S: AsRef<str>>(self, ipv6: S) -> Self {
        let ipv6 = Some(ipv6.as_ref().to_string());
        Self { ipv6, ..self }
    }

    /// Specifies an explicit IP address as an `IpAddr' object.
    /// Handles both V4 and V6 variants internally.
    pub fn ip(self, ip: IpAddr) -> Self {
        match ip {
            IpAddr::V4(ipv4) => self.ipv4(ipv4.to_string()),
            IpAddr::V6(ipv6) => self.ipv6(ipv6.to_string()),
        }
    }

    /// Asks for verbose output.
    pub fn verbose(self) -> Self {
        Self {
            verbose: true,
            ..self
        }
    }

    /// Directs DuckDNS to clear your record.
    pub fn clear(self) -> Self {
        Self {
            clear: true,
            ..self
        }
    }

    /// Executes actual update call to the DuckDNS service
    pub fn update(&self) -> reqwest::Result<()> {
        let url = self.url();
        let mut status = reqwest::get(&url)?;

        assert_eq!(status.text()?, "OK");

        Ok(())
    }

    fn url(&self) -> String {
        assert!(self.domains.is_some());

        let mut url = format!("{}?token={}", DUCKDNS_URL, self.token);

        if let Some(ref domains) = self.domains {
            url += &format!("&domains={}", domains);
        }

        if let Some(ref ipv4) = self.ipv4 {
            url += &format!("&ip={}", ipv4);
        }

        if let Some(ref ipv6) = self.ipv6 {
            url += &format!("&ipv6={}", ipv6);
        }

        if self.verbose {
            url += "&verbose=true";
        }

        if self.clear {
            url += "&clear=true";
        }

        url
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn simple() {
        let url = DuckDns::new("dummy").domains("foo.net").url();
        assert_eq!(url, format!("{}?token=dummy&domains=foo.net", DUCKDNS_URL));
    }

    #[test]
    fn ipv4() {
        let url = DuckDns::new("dummy")
            .domains("foo.net")
            .ipv4("127.0.0.2")
            .url();
        assert_eq!(
            url,
            format!("{}?token=dummy&domains=foo.net&ip=127.0.0.2", DUCKDNS_URL)
        );
        let ip = "123.45.67.89".parse().unwrap();
        let url = DuckDns::new("dummy").domains("foo.net").ip(ip).url();
        assert_eq!(
            url,
            format!(
                "{}?token=dummy&domains=foo.net&ip=123.45.67.89",
                DUCKDNS_URL
            )
        );
    }

    #[test]
    fn ipv6() {
        let url = DuckDns::new("dummy").domains("foo.net").ipv6("::1").url();
        assert_eq!(
            url,
            format!("{}?token=dummy&domains=foo.net&ipv6=::1", DUCKDNS_URL)
        );
        let ip = "2002:DB7::21f:5bff:febf:ce22:8a2e".parse().unwrap();
        let url = DuckDns::new("dummy").domains("foo.net").ip(ip).url();
        assert_eq!(
            url,
            format!(
                "{}?token=dummy&domains=foo.net&ipv6=2002:db7:0:21f:5bff:febf:ce22:8a2e",
                DUCKDNS_URL
            )
        );
    }

    #[test]
    fn verbose() {
        let url = DuckDns::new("dummy").domains("foo.net").verbose().url();
        assert_eq!(
            url,
            format!("{}?token=dummy&domains=foo.net&verbose=true", DUCKDNS_URL)
        );
    }

    #[test]
    fn clear() {
        let url = DuckDns::new("dummy").domains("foo.net").clear().url();
        assert_eq!(
            url,
            format!("{}?token=dummy&domains=foo.net&clear=true", DUCKDNS_URL)
        );
    }
}