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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use std::io::{Write, Read};

const TEXT_PARAM: &'static str = "text";
const TOKEN_PARAM: &'static str = "TOKEN";
const SHORTHASH_PARAM: &'static str = "shortHash";
pub const URL_PARAM: &'static str = "RCLIP_URL";
const OPEN_ENDPOINT: &'static str = "dev/open";
const LINK_ENDPONT: &'static str = "dev/link";
const COPY_ENDPOINT: &'static str = "dev/push";
const PASTE_ENDPONT: &'static str = "dev/pull";

pub mod config;
pub mod stream;
mod http;

#[derive(Debug)]
pub enum ClipboardError {
    NetworkError(String),
    BackendError,
}

pub struct Clipboard {
    pub config: config::ConfigContext,
}

impl Clipboard {

    pub fn from(config: config::ConfigContext) -> Clipboard {
        Clipboard {
            config: config,
        }
    }

    /// Push readable data into the remote clipboard
    ///
    /// # Arguments
    ///
    /// * `input` - A readable object
    ///
    /// # Example
    ///
    /// ```
    /// use remote_clipboard as rclip;
    /// use std::path::PathBuf;
    /// use url::Url;
    /// let clipboard = rclip::Clipboard::from(rclip::config::ConfigContext {
    ///     config_path: PathBuf::from("/blah"),
    ///     base_url: url::Url::parse("https://toto.com").unwrap(),
    ///     token: String::from("token"),
    /// });
    /// clipboard.push(&mut "toto".as_bytes());
    /// ```
    pub fn push(&self, input: &mut dyn Read) -> Result<(), ClipboardError> {
        let mut url = http::prepare_endpoint(&self.config, COPY_ENDPOINT);
        http::append_query(&mut url, input, &TEXT_PARAM);
        http::get_http(&url)
    }

    /// Pull data from the remote clipboard
    /// # Example
    ///
    /// ```
    /// use remote_clipboard as rclip;
    /// use std::io::{self};
    /// use std::path::PathBuf;
    /// use url::Url;
    /// let clipboard = rclip::Clipboard::from(rclip::config::ConfigContext {
    ///     config_path: PathBuf::from("/blah"),
    ///     base_url: url::Url::parse("https://toto.com").unwrap(),
    ///     token: String::from("token"),
    /// });
    /// let stdout = io::stdout();
    /// clipboard.pull(&mut stdout.lock());
    /// ```
    pub fn pull(&self, output: &mut dyn Write) -> Result<(), ClipboardError> {
        let url = http::prepare_endpoint(&self.config, PASTE_ENDPONT);
        let resp = http::get_http_response(&url)?;
        let _ = match resp.get(&String::from(TEXT_PARAM)) {
            Some(number) => output.write(number.as_ref()),
            _ => output.write(b""),
        };
        Ok(())
    }

    /// Open a new remote clipboard
    /// and display a short living hash for linking
    /// another client.
    /// # Example
    ///
    /// ```
    /// use remote_clipboard as rclip;
    /// use std::path::PathBuf;
    /// use url::Url;
    /// let mut clipboard = rclip::Clipboard::from(rclip::config::ConfigContext {
    ///     config_path: PathBuf::from("/blah"),
    ///     base_url: url::Url::parse("https://toto.com").unwrap(),
    ///     token: String::from("token"),
    /// });
    /// clipboard.open();
    /// ```
    pub fn open(&mut self) -> Result<(), ClipboardError> {
        let url = http::prepare_endpoint(&self.config, OPEN_ENDPOINT);
        let resp = http::get_http_response(&url)?;
        match resp.get(&String::from(TEXT_PARAM)) {
            Some(token) => { self.config.token = token.clone(); Ok(()) },
            _ => Err(ClipboardError::BackendError)
        }
    }

    /// Link against newly opened remote clipboard
    ///
    /// # Arguments
    ///
    /// * `input` - A readable object containing the short living hash
    ///
    /// # Example
    ///
    /// ```
    /// use remote_clipboard as rclip;
    /// use std::io::{self};
    /// use std::path::PathBuf;
    /// use url::Url;
    /// let mut clipboard = rclip::Clipboard::from(rclip::config::ConfigContext {
    ///     config_path: PathBuf::from("/blah"),
    ///     base_url: url::Url::parse("https://toto.com").unwrap(),
    ///     token: String::from("token"),
    /// });
    /// clipboard.link(&mut "012345".as_bytes());
    /// ```
    /// TODO: check input size
    pub fn link(&mut self, input: &mut dyn Read) -> Result<(), ClipboardError> {
        let mut url = http::prepare_endpoint(&self.config, LINK_ENDPONT);
        http::append_query(&mut url, input, SHORTHASH_PARAM);
        let resp = http::get_http_response(&url)?;
        match resp.get(&String::from(TOKEN_PARAM)) {
            Some(token) => {self.config.token = token.clone(); Ok(())},
            _ => Err(ClipboardError::BackendError),
        }
    }
}


#[cfg(test)]
mod tests {

    use crate::config::ConfigContext;
    use mocktopus::mocking::*;
    use std::path::PathBuf;
    use std::io::{self};
    use super::*;

    fn mocked_config() -> ConfigContext {
        ConfigContext {
            config_path: PathBuf::from("/blah"),
            base_url: url::Url::parse("https://toto.com").unwrap(),
            token: String::from("token"),
        }
    }

    #[test]
    fn check_push() {
        http::get_http.mock_safe(|_url| MockResult::Return(Ok(())));
        let clipboard = Clipboard::from(mocked_config());

        let _ = clipboard.push(&mut "toto".as_bytes());
    }

    #[test]
    fn check_pull() {
        http::get_http_response.mock_safe(|_url|
            MockResult::Return(Ok(vec![(TEXT_PARAM.to_string(), "stuff".to_string())]
                .into_iter().collect())));
        let clipboard = Clipboard::from(mocked_config());
        let stdout = io::stdout();

        let _ = clipboard.pull(&mut stdout.lock());
    }

    #[test]
    fn check_open() {
        http::get_http_response.mock_safe(|_url|
            MockResult::Return(Ok(vec![(TEXT_PARAM.to_string(), "012345".to_string())]
                .into_iter().collect())));
        let mut clipboard = Clipboard::from(mocked_config());

        let _ = clipboard.open();
    }

    #[test]
    #[should_panic]
    fn check_open_panic() {
        http::get_http_response.mock_safe(|_url|
            MockResult::Return(Ok(vec![("nonexist".to_string(), "01234".to_string())]
                .into_iter().collect())));
        let mut clipboard = Clipboard::from(mocked_config());

        clipboard.open().unwrap();
    }

    #[test]
    fn check_link() {
        http::get_http_response.mock_safe(|_url|
            MockResult::Return(Ok(vec![(TOKEN_PARAM.to_string(), "stuff".to_string())].into_iter().collect())));
        let mut clipboard = Clipboard::from(mocked_config());

        let _ = clipboard.link(&mut "toto".as_bytes());
    }

}