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
extern crate crypto;
extern crate libflate;
extern crate ndarray;
extern crate reqwest;
extern crate tokio;
use super::super::utils::natural_transform::opt_to_failure;
use bytes::Bytes;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use failure::Error;
use futures_util::stream::{self, StreamExt};
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{self, PathBuf};
fn remove_ext(fname: &str) -> Result<PathBuf, Error> {
Ok(PathBuf::from(opt_to_failure(
opt_to_failure(
PathBuf::from(fname).file_stem(),
"Cannot dedude the name of unarchived file from archived file",
)?
.to_str(),
"Cannot convert native string",
)?))
}
#[derive(Debug)]
pub struct RemoteFile<'a> {
pub host_and_path: &'a str,
pub fname: &'a str,
pub sha256: &'a str,
pub query: &'a str,
}
impl<'a> fmt::Display for RemoteFile<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"host_and_path: {}\n file name: {}\n sha256 hash: {}\n reqest query: {}",
self.host_and_path, self.fname, self.sha256, self.query
)
}
}
impl<'a> RemoteFile<'a> {
pub fn new(host_and_path: &'a str, fname: &'a str, sha256: &'a str, query: &'a str) -> Self {
Self {
host_and_path: host_and_path,
fname: fname,
sha256: sha256,
query: query,
}
}
}
pub struct FConf<'a, T>
where
T: Iterator<Item = &'a RemoteFile<'a>> + ExactSizeIterator,
{
pub save_dir_name: &'a str,
pub remote_file: T,
}
impl<'a, T> FConf<'a, T>
where
T: Iterator<Item = &'a RemoteFile<'a>> + ExactSizeIterator,
{
pub fn new(save_dir_name: &'a str, rf: T) -> Self {
Self {
save_dir_name: save_dir_name,
remote_file: rf,
}
}
}
#[derive(Clone)]
pub struct FileInfo<'a> {
pub host_and_path: &'a str,
pub sha256: &'a str,
pub query: &'a str,
}
#[derive(Clone)]
pub struct DirClient<'a> {
save_dir: PathBuf,
pub file: HashMap<String, FileInfo<'a>>,
}
impl<'a> DirClient<'a> {
pub fn new<T>(cfg: FConf<'a, T>) -> io::Result<Self>
where
T: Iterator<Item = &'a RemoteFile<'a>> + ExactSizeIterator,
{
let mut current_path = env::current_dir()?;
current_path.push(cfg.save_dir_name);
let mut hash = HashMap::new();
for elem in cfg.remote_file {
hash.insert(
elem.fname.to_string(),
FileInfo {
host_and_path: elem.host_and_path,
sha256: elem.sha256,
query: elem.query,
},
);
}
Ok(Self {
save_dir: current_path,
file: hash,
})
}
fn path(&self) -> &path::Path {
self.save_dir.as_path()
}
pub fn file_path(&self, fname: &str) -> PathBuf {
self.save_dir.join(PathBuf::from(fname))
}
pub fn create(&self) -> io::Result<()> {
if !self.exists() {
return fs::create_dir(self.path());
}
Ok(())
}
pub fn file_create(&self, dst: &str, src: &mut Bytes) -> io::Result<()> {
let mut out = File::create(self.file_path(dst))?;
out.write(&src)?;
Ok(())
}
pub fn exists(&self) -> bool {
self.save_dir.exists()
}
pub fn file_exists(&self, fname: &str) -> bool {
self.file_path(fname).exists()
}
pub fn rm_file(&self, fname: &str) -> Result<(), Error> {
if self.exists() && self.file_exists(fname) {
if let Err(e) = fs::remove_file(self.file_path(fname)) {
Err(failure::format_err!("{}", e.to_string()))
} else {
Ok(())
}
} else {
Err(failure::format_err!("no such file"))
}
}
}
#[derive(Clone)]
pub struct FetchClient<'a> {
pub dir_client: DirClient<'a>,
}
impl<'a> FetchClient<'a> {
pub fn new<T>(cfg: FConf<'a, T>) -> io::Result<Self>
where
T: Iterator<Item = &'a RemoteFile<'a>> + ExactSizeIterator,
{
Ok(Self {
dir_client: DirClient::new(cfg)?,
})
}
fn is_exists(&self) -> io::Result<bool> {
Ok(self.dir_client.exists()
&& self.dir_client.file.keys().fold(true, |acc, val| {
acc && (self.dir_client.file_exists(val) || {
if let Ok(s) = remove_ext(val) {
if let Some(s) = s.to_str() {
self.dir_client.file_exists(&s.to_string())
} else {
false
}
} else {
false
}
})
}))
}
async fn fetch(&self, fname: &str) -> reqwest::Result<Option<bytes::Bytes>> {
if let Some(elem) = self.dir_client.file.get(fname) {
println!("Fetching {} from {}{}", fname, elem.host_and_path, fname);
let q = if elem.query.len() == 0 { "" } else { "?" };
Ok(Some(
reqwest::get(&(elem.host_and_path.to_owned() + fname + q + elem.query))
.await?
.bytes()
.await?,
))
} else {
Ok(None)
}
}
fn check_hash(&self, fname: &str, buf: &bytes::Bytes) -> io::Result<()> {
println!("Checking hash {}...", fname);
let mut sha256 = Sha256::new();
sha256.input(buf.as_ref());
if let Some(elem) = self.dir_client.file.get(fname) {
if elem.sha256 != sha256.result_str() {
return Err(io::Error::new(
io::ErrorKind::Other,
"sha256 hash value does not match",
));
} else {
println!("sha256 hash value of file {} matched", fname);
return Ok(());
}
}
Err(io::Error::new(
io::ErrorKind::NotFound,
"the specified file is invalid",
))
}
pub fn get(&self) -> io::Result<()> {
if self.is_exists()? {
println!("the specified data is already saved.");
return Ok(());
}
println!("Start to download and setup data (only first time execute)...");
let mut rt = tokio::runtime::Runtime::new()?;
self.dir_client
.create()
.expect("failed to create directory");
rt.block_on(
stream::iter(self.dir_client.file.keys()).fold(Ok(()), |acc, kf| async move {
if let Err(_) = acc {
acc
} else {
match self.fetch(kf).await {
Err(e) => Err(io::Error::new(io::ErrorKind::Other, e.to_string())),
Ok(Some(mut s)) => {
self.check_hash(kf, &s)?;
self.dir_client.file_create(kf, &mut s)
}
Ok(None) => Err(io::Error::new(
io::ErrorKind::Other,
"the specified file is invalid",
)),
}
}
}),
)
}
}