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
use std::io::{self, Write, Read}; use std::process; const TEXT_PARAM: &'static str = "text"; const TOKEN_PARAM: &'static str = "TOKEN"; const URL_PARAM: &'static str = "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"; const HASH_SHORT_SIZE: usize = 6; mod config; mod http; pub fn push(input: &mut dyn Read) { let config_context = config::load_config(); if config_context.token.is_empty() { fail("No clipboard linked, please link or open a new clipboard"); } let mut url = http::prepare_endpoint(&config_context, COPY_ENDPOINT); http::append_query(&mut url, input, &TEXT_PARAM); http::get_http_or_fail(&url); } pub fn pull(stdout: io::Stdout) { let config_context = config::load_config(); if config_context.token.is_empty() { fail("No clipboard linked, please link or open a new clipboard"); } let url = http::prepare_endpoint(&config_context, PASTE_ENDPONT); let resp = http::get_http_response_or_fail(&url); let _ = match resp.get(&String::from(TEXT_PARAM)) { Some(number) => stdout.lock().write(number.as_ref()), _ => stdout.lock().write(b""), }; } pub fn open(stdout: io::Stdout) { let config_context = config::load_config(); let url = http::prepare_endpoint(&config_context, OPEN_ENDPOINT); let resp = http::get_http_response_or_fail(&url); let _ = match resp.get(&String::from(TEXT_PARAM)) { Some(token) => { config::store_config(&config_context, &token); stdout.lock().write(&token.as_bytes()[..HASH_SHORT_SIZE]) }, _ => fail("Failed to open new link with back-end"), }; } pub fn link(stdout: io::Stdout, input: &mut dyn Read) { let config_context = config::load_config(); let mut url = http::prepare_endpoint(&config_context, LINK_ENDPONT); http::append_query(&mut url, input, TEXT_PARAM); let resp = http::get_http_response_or_fail(&url); let _ = match resp.get(&String::from(TOKEN_PARAM)) { Some(token) => { config::store_config(&config_context, &token); stdout.lock().write(token.as_ref()) }, _ => fail("Failed to link with the back-end"), }; } pub fn fail(s: &str) -> ! { let stderr = io::stderr(); let mut stderr = stderr.lock(); let _ = stderr.write(format!("{}{}{}", "error: ", s, "\n").as_bytes()); let _ = stderr.flush(); process::exit(1); }