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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
use crate::error::{self, TinifyException};
use reqwest::blocking::Client as BlockingClient;
use reqwest::blocking::Response as ReqwestResponse;
use reqwest::Error as ReqwestError;
use reqwest::StatusCode;
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::time::Duration;
use std::path::Path;
use std::fs::File;
use std::process;
use std::str;
type TinifyError = ReqwestError;
type TinifyResponse = ReqwestResponse;
const API_ENDPOINT: &str = "https://api.tinify.com";
pub enum Method {
Post,
Get,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Source {
url: Option<String>,
key: Option<String>,
buffer: Option<Vec<u8>>,
}
impl Source {
pub fn new(url: Option<String>, key: Option<String>) -> Self {
Self {
url,
key,
buffer: None,
}
}
pub fn request(
&self,
method: Method,
url: &str,
buffer: Option<&[u8]>,
) -> Result<TinifyResponse, TinifyError> {
let full_url = format!("{}{}", API_ENDPOINT, url);
let reqwest_client = BlockingClient::new();
let timeout = Duration::from_secs(240);
let response = match method {
Method::Post => {
reqwest_client
.post(full_url)
.body(buffer.unwrap().to_owned())
.basic_auth("api", self.key.as_ref())
.timeout(timeout)
.send()
},
Method::Get => {
reqwest_client
.get(url)
.timeout(timeout)
.send()
},
};
if let Err(error) = response.as_ref() {
if error.is_connect() {
eprintln!("Error processing the request.");
process::exit(1);
}
}
let request_status = response.as_ref().unwrap().status();
match request_status {
StatusCode::UNAUTHORIZED => {
error::exit_error(
TinifyException::AccountException,
&request_status
);
},
StatusCode::UNSUPPORTED_MEDIA_TYPE => {
error::exit_error(
TinifyException::ClientException,
&request_status
);
},
StatusCode::SERVICE_UNAVAILABLE => {
error::exit_error(
TinifyException::ServerException,
&request_status
);
},
_ => {},
};
response
}
pub fn from_file(self, path: &Path) -> Result<Self, TinifyException> {
let location = Path::new(path);
if !location.exists() {
return Err(TinifyException::NoFileOrDirectory);
}
let file = File::open(path).unwrap();
let mut reader = BufReader::new(file);
let mut buffer: Vec<u8> = Vec::with_capacity(reader.capacity());
reader.read_to_end(&mut buffer).unwrap();
Ok(self.from_buffer(&buffer))
}
pub fn from_buffer(self, buffer: &[u8]) -> Self {
let response =
self.request(Method::Post, "/shrink", Some(buffer));
self.get_source_from_response(response.unwrap())
}
pub fn from_url(self, url: &str) -> Result<Self, TinifyException> {
let get = self.request(Method::Get, url, None);
let bytes = get.unwrap().bytes().unwrap().to_vec();
let post = self.request(Method::Post, "/shrink", Some(&bytes));
Ok(self.get_source_from_response(post.unwrap()))
}
pub fn get_source_from_response(
mut self,
response: TinifyResponse,
) -> Self {
let optimized_location =
response.headers().get("location").unwrap();
let mut url = String::new();
if !optimized_location.is_empty() {
let slice =
str::from_utf8(optimized_location.as_bytes()).unwrap();
url.push_str(slice);
}
let get = self.request(Method::Get, &url, None);
let bytes = get.unwrap().bytes().unwrap().to_vec();
self.buffer = Some(bytes);
self.url = Some(url);
self
}
pub fn to_file(&self, path: &str) -> io::Result<()> {
let file = File::create(path)?;
let mut reader = BufWriter::new(file);
reader.write_all(self.buffer.as_ref().unwrap())?;
reader.flush()?;
Ok(())
}
pub fn to_buffer(&self) -> Vec<u8> {
self.buffer.as_ref().unwrap().to_vec()
}
}
#[cfg(test)]
mod tests {
use super::*;
use dotenv::dotenv;
use std::env;
use std::fs;
fn get_key() -> String {
let key = match env::var("KEY") {
Ok(key) => key,
Err(_err) => panic!("No such file or directory."),
};
key
}
#[test]
fn test_get_request() -> Result<(), TinifyError> {
let source = Source::new(None, None);
let url = "https://tinypng.com/images/panda-happy.png";
let _ = source.request(Method::Get, url, None)?;
Ok(())
}
#[test]
fn test_post_request() -> Result<(), TinifyError> {
dotenv().ok();
let key = get_key();
let source = Source::new(None, Some(key));
let path = Path::new("./tmp_image.jpg");
let bytes = fs::read(path).unwrap();
let _ = source
.request(Method::Post, "/shrink", Some(&bytes))?;
Ok(())
}
#[test]
fn test_from_file() -> Result<(), TinifyException> {
dotenv().ok();
let key = get_key();
let path = Path::new("./tmp_image.jpg");
let source = Source::new(None, Some(key));
let _ = source.from_file(path)?;
Ok(())
}
#[test]
fn test_from_url() -> Result<(), TinifyException> {
dotenv().ok();
let key = get_key();
let url = "https://tinypng.com/images/panda-happy.png";
let _ = Source::new(None, Some(key)).from_url(url)?;
Ok(())
}
#[test]
fn test_get_source_from_response() {
let key = get_key();
let path = Path::new("./tmp_image.jpg");
let source = Source::new(None, Some(key.clone()));
let bytes = fs::read(path).unwrap();
let get = source.request(Method::Post, "/shrink", Some(&bytes)).unwrap();
let actual = source.get_source_from_response(get);
let mut expected = Source::new(None, Some(key.clone()));
expected.buffer = actual.buffer.clone();
expected.url = actual.url.clone();
assert_eq!(actual, expected);
}
#[test]
fn test_to_file() {
let key = get_key();
let tmp = "./tmp_image.jpg";
let location = "./new_image.jpg";
let bytes = fs::read(tmp).unwrap();
let mut source = Source::new(None, Some(key.clone()));
source.buffer = Some(bytes);
let _ = source.to_file(location);
let exists = Path::exists(Path::new(location));
assert!(exists);
if exists {
fs::remove_file(location).unwrap();
}
}
#[test]
fn test_to_buffer() {
let tmp = "./tmp_image.jpg";
let expected = fs::read(tmp).unwrap();
let mut source = Source::new(None, None);
source.buffer = Some(expected.clone());
let actual = source.to_buffer();
assert_eq!(actual, expected);
}
}