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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
use hyper::{self, Client};
use hyper::client::Body;
use hyper::client::response::Response;
use hyper::header::{ContentLength,ContentType,CacheControl};
use serde::Deserialize;
use serde_json;
use serde_json::value::{Value as JsonValue};
use serde_json::map::Map;
use B2Error;
use B2AuthHeader;
use raw::authorize::B2Authorization;
use raw::files::FileInfo;
header! { (XBzFileId, "X-Bz-File-Id") => [String] }
header! { (XBzUploadTimestamp, "X-Bz-Upload-Timestamp") => [String] }
header! { (XBzFileName, "X-Bz-File-Name") => [String] }
header! { (XBzContentSha1, "X-Bz-Content-Sha1") => [String] }
#[derive(Serialize,Deserialize,Clone,Debug)]
#[serde(rename_all = "camelCase")]
pub struct DownloadAuthorization<'a> {
pub authorization_token: String,
pub bucket_id: Option<String>,
pub file_name_prefix: String,
pub download_url: &'a str
}
impl<'a> DownloadAuthorization<'a> {
pub fn auth_header(&self) -> B2AuthHeader {
B2AuthHeader(self.authorization_token.clone())
}
pub fn allows_bucket(&self, bucket: &str) -> bool {
match self.bucket_id {
Some(ref s) => s == bucket,
None => true
}
}
}
fn handle_download_response<InfoType>(resp: Response)
-> Result<(Response, Option<FileInfo<InfoType>>), B2Error>
where for<'de> InfoType: Deserialize<'de>
{
loop {
let file_id = match resp.headers.get::<XBzFileId>() {
Some(header) => format!("{}", header),
None => break
};
let file_name = match resp.headers.get::<XBzFileName>() {
Some(header) => format!("{}", header),
None => break
};
let content_length = match resp.headers.get::<ContentLength>() {
Some(header) => header.0,
None => break
};
let content_type = match resp.headers.get::<ContentType>() {
Some(header) => format!("{}", header),
None => break
};
let content_sha1 = match resp.headers.get::<XBzContentSha1>() {
Some(header) => format!("{}", header),
None => break
};
let upload_timestamp = match resp.headers.get::<XBzUploadTimestamp>() {
Some(header) => format!("{}", header),
None => break
};
let mut info = Map::new();
let check_headers = if resp.headers.has::<CacheControl>() {
resp.headers.len() > 7
} else {
resp.headers.len() > 6
};
if check_headers {
for header in resp.headers.iter() {
if header.name().starts_with("X-Bz-Info-") {
info.insert(header.name()[10..].to_owned(),
JsonValue::String(header.value_string()));
}
}
}
return Ok((resp, Some(FileInfo {
file_id: file_id,
file_name: file_name,
content_length: content_length,
content_type: content_type,
content_sha1: content_sha1,
file_info: serde_json::from_value(JsonValue::Object(info))?,
upload_timestamp: match upload_timestamp.parse() {
Ok(v) => v,
Err(_) => return Err(B2Error::LibraryError("upload timestamp not integer".to_owned()))
},
})));
}
Ok((resp, None))
}
impl<'a> DownloadAuthorization<'a> {
pub fn download_file_by_id<InfoType>(&self, file_id: &str, client: &Client)
-> Result<(Response, Option<FileInfo<InfoType>>), B2Error>
where for<'de> InfoType: Deserialize<'de>
{
let url_string: String = format!("{}/b2api/v1/b2_download_file_by_id", self.download_url);
let url: &str = &url_string;
let body: String = format!("{{\"fileId\":\"{}\"}}", file_id);
let resp = try!(client.post(url)
.body(Body::BufBody(body.as_bytes(), body.len()))
.header(self.auth_header())
.send());
if resp.status != hyper::status::StatusCode::Ok {
Err(B2Error::from_response(resp))
} else {
handle_download_response(resp)
}
}
pub fn download_range_by_id<InfoType>(&self, file_id: &str, range_min: u64, range_max: u64, client: &Client)
-> Result<(Response, Option<FileInfo<InfoType>>), B2Error>
where for<'de> InfoType: Deserialize<'de>
{
let url_string: String = format!("{}/b2api/v1/b2_download_file_by_id", self.download_url);
let url: &str = &url_string;
let body: String = format!("{{\"fileId\":\"{}\"}}", file_id);
let resp = try!(client.post(url)
.body(Body::BufBody(body.as_bytes(), body.len()))
.header(self.auth_header())
.header(B2Range(format!("bytes={}-{}", range_min, range_max)))
.send());
if resp.status != hyper::status::StatusCode::PartialContent {
Err(B2Error::from_response(resp))
} else {
handle_download_response(resp)
}
}
pub fn download_file_by_name<InfoType>(&self, bucket_name: &str, file_name: &str, client: &Client)
-> Result<(Response, Option<FileInfo<InfoType>>), B2Error>
where for<'de> InfoType: Deserialize<'de>
{
let url_string: String = format!("{}/file/{}/{}", self.download_url, bucket_name, file_name);
let url: &str = &url_string;
let resp = try!(client.get(url)
.header(self.auth_header())
.send());
if resp.status != hyper::status::StatusCode::Ok {
Err(B2Error::from_response(resp))
} else {
handle_download_response(resp)
}
}
pub fn download_range_by_name<InfoType>(&self, bucket_name: &str, file_name: &str,
range_min: u64, range_max: u64, client: &Client)
-> Result<(Response, Option<FileInfo<InfoType>>), B2Error>
where for<'de> InfoType: Deserialize<'de>
{
let url_string: String = format!("{}/file/{}/{}", self.download_url, bucket_name, file_name);
let url: &str = &url_string;
let resp = try!(client.get(url)
.header(self.auth_header())
.header(B2Range(format!("bytes={}-{}", range_min, range_max)))
.send());
if resp.status != hyper::status::StatusCode::PartialContent {
Err(B2Error::from_response(resp))
} else {
handle_download_response(resp)
}
}
}
header! { (B2Range, "Range") => [String] }
impl<'a> B2Authorization<'a> {
pub fn to_download_authorization(&self) -> DownloadAuthorization {
DownloadAuthorization {
authorization_token: self.authorization_token.clone(),
bucket_id: None,
file_name_prefix: "".to_owned(),
download_url: &self.download_url
}
}
pub fn get_download_authorization<'s>(&'s self, bucket_id: &str, file_name_prefix: Option<&str>,
expires_in_seconds: u32, client: &Client)
-> Result<DownloadAuthorization<'s>, B2Error>
{
let url_string: String = format!("{}/b2api/v1/b2_get_download_authorization", self.api_url);
let url: &str = &url_string;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Request<'a> {
bucket_id: &'a str,
file_name_prefix: &'a str,
valid_duration_in_seconds: u32
}
let request = Request {
bucket_id: bucket_id,
file_name_prefix: match file_name_prefix {
Some(v) => v,
None => ""
},
valid_duration_in_seconds: expires_in_seconds
};
#[derive(Serialize,Deserialize,Clone,Debug)]
#[serde(rename_all = "camelCase")]
pub struct Response {
authorization_token: String,
bucket_id: String,
file_name_prefix: String
}
let body: String = serde_json::to_string(&request)?;
let resp = client.post(url)
.body(Body::BufBody(body.as_bytes(), body.len()))
.header(self.auth_header())
.send()?;
if resp.status != hyper::status::StatusCode::Ok {
Err(B2Error::from_response(resp))
} else {
let Response {
authorization_token, bucket_id, file_name_prefix
} = serde_json::from_reader(resp)?;
Ok(DownloadAuthorization {
authorization_token: authorization_token,
bucket_id: Some(bucket_id),
file_name_prefix: file_name_prefix,
download_url: &self.download_url
})
}
}
}
pub fn download_file_by_name<InfoType>(download_url: &str, bucket_name: &str, file_name: &str, client: &Client)
-> Result<(Response, Option<FileInfo<InfoType>>), B2Error>
where for<'de> InfoType: Deserialize<'de>
{
let url_string: String = format!("{}/file/{}/{}", download_url, bucket_name, file_name);
let url: &str = &url_string;
let resp = try!(client.post(url)
.send());
if resp.status != hyper::status::StatusCode::Ok {
Err(B2Error::from_response(resp))
} else {
handle_download_response(resp)
}
}
pub fn download_range_by_name<InfoType>(download_url: &str, bucket_name: &str, file_name: &str,
range_min: u64, range_max: u64, client: &Client)
-> Result<(Response, Option<FileInfo<InfoType>>), B2Error>
where for<'de> InfoType: Deserialize<'de>
{
let url_string: String = format!("{}/file/{}/{}", download_url, bucket_name, file_name);
let url: &str = &url_string;
let resp = try!(client.get(url)
.header(B2Range(format!("bytes={}-{}", range_min, range_max)))
.send());
if resp.status != hyper::status::StatusCode::PartialContent {
Err(B2Error::from_response(resp))
} else {
handle_download_response(resp)
}
}