goxoy_file_chunker/
file_chunker.rs

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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use rand::Rng;
use serde::*;
use serde_json::*;
use std::collections::HashMap;
use std::fs::{self, create_dir_all, File};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use substring::Substring;
use zip::write::FileOptions;
use zip::{ZipArchive, ZipWriter};
use data_encoding::Specification;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
pub enum DefaultStoragePath {
    ExePath,
    TempPath,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
pub enum FileChunkType {
    Byte,
    KiloByte,
    MegaByte,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileChunkSplitResult {
    pub info_file: String,
    pub file_name: String,
    pub file_hash: String,
    pub file_size: usize,
    pub chunk_size: usize,
    pub chunk_count: usize,
    pub list: HashMap<usize, (String, String)>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileChunk {
    pub is_exist: bool,
    pub file_name: String,
    pub file_size: u128,
    pub file_hash: String,
    pub chunk_size: u128,
    pub chunk_type: FileChunkType,
    pub storage_path: String,
    pub compress_active: bool,
    pub result_obj: FileChunkSplitResult,
    pub result_list: Vec<String>,
}

impl FileChunk {
    pub fn new() -> Self {
        FileChunk {
            is_exist: false,
            file_name: String::new(),
            file_size: 0,
            file_hash: String::new(),
            chunk_size: 256,
            chunk_type: FileChunkType::KiloByte,
            storage_path: String::new(),
            compress_active: false,
            result_obj: FileChunkSplitResult {
                info_file: String::new(),
                file_name: String::new(),
                file_hash: String::new(),
                file_size: 0,
                chunk_size: 0,
                chunk_count: 0,
                list: HashMap::new(),
            },
            result_list:Vec::new()
        }
    }
    #[allow(dead_code)]
    fn hex_to_base32(&self, hex_str: String) -> String {
        let decoded = hex::decode(hex_str).unwrap();
        let spec_hex = {
            let mut spec = Specification::new();
            spec.symbols.push_str("0123456789abcdefghijklmnoprstuvy");
            spec.encoding().unwrap()
        };
        spec_hex.encode(&decoded)
    }
    fn calculate_file_hash(&self, file_path: String) -> String {
        let bytes = fs::read(file_path).unwrap();
        format!("{}", blake3::hash(&bytes).to_hex())
    }
    fn control_storage_path(&self) {
        _ = create_dir_all(self.storage_path.clone());
    }
    pub fn set_compress(&mut self, active: bool) {
        self.compress_active = active;
    }
    pub fn set_storage_path_with_string(&mut self, storage_path: &str) {
        self.storage_path = storage_path.to_string();
        self.control_storage_path();
    }
    pub fn set_storage_path(&mut self, which_path: DefaultStoragePath) {
        match which_path {
            DefaultStoragePath::ExePath => {
                let mut c_path = std::env::current_exe().unwrap();
                // c_path.pop();
                c_path.pop();
                c_path.pop();
                c_path.pop();
                c_path.push("storages");
                self.storage_path = format!("{}", c_path.display());
            }
            DefaultStoragePath::TempPath => {
                self.storage_path = format!("{}", std::env::temp_dir().to_str().unwrap());
            }
        }
        self.control_storage_path();
    }
    pub fn assign_file(&mut self, file_path: &str) {
        let file_meta = fs::metadata(file_path);
        if file_meta.is_ok() {
            self.is_exist = true;
            self.file_name = String::from(file_path);
            self.file_size = file_meta.unwrap().len() as u128;
            self.file_hash = self.calculate_file_hash(file_path.to_string());
        } else {
            self.is_exist = false;
            self.file_hash = String::new();
            self.file_size = 0;
            self.file_name = String::new();
            self.chunk_size = 256;
            self.chunk_type = FileChunkType::KiloByte;
        }
    }
    pub fn set_size(&mut self, chunk_size: u128, chunk_type: FileChunkType) {
        self.chunk_size = chunk_size;
        self.chunk_type = chunk_type;
    }
    fn chunk_size(&self) -> u128 {
        match self.chunk_type {
            FileChunkType::Byte => self.chunk_size,
            FileChunkType::KiloByte => self.chunk_size * 1024,
            FileChunkType::MegaByte => self.chunk_size * 1024 * 1024,
        }
    }
    pub fn split(&mut self) -> (bool, String) {
        self.result_list.clear();
        if self.storage_path.len() == 0 {
            self.set_storage_path(DefaultStoragePath::ExePath);
        }

        let current_chunk_size = self.chunk_size();
        if current_chunk_size < 16384 {
            self.chunk_type = FileChunkType::KiloByte;
            self.chunk_size = 64;
        }
        let mut tmp_chunk_dir = self.storage_path.clone();
        tmp_chunk_dir.push(std::path::MAIN_SEPARATOR);
        tmp_chunk_dir.push_str(&self.file_hash);
        let clear_folder_name = tmp_chunk_dir.clone();
        _ = create_dir_all(tmp_chunk_dir.clone());
        let mut split_error = false;
        let mut counter = 1;
        let file = File::open(&self.file_name).unwrap();
        let mut reader = BufReader::with_capacity(self.chunk_size() as usize, file);
        let mut file_hash_list = HashMap::new();
        loop {
            let extension_str = format!("{:0>8}", counter.to_string());
            let buffer = reader.fill_buf();
            if buffer.is_ok() {
                let buffer = buffer.unwrap();
                let buffer_length = buffer.len();
                if buffer_length == 0 {
                    break;
                }
                let raw_file_name = format!("chunk.{}", extension_str.clone());

                let mut tmp_file_name = tmp_chunk_dir.clone();
                tmp_file_name.push(std::path::MAIN_SEPARATOR);
                tmp_file_name.push_str(&raw_file_name.clone());
                let create_obj = std::fs::File::create(tmp_file_name.clone());
                if create_obj.is_ok() {
                    let mut f_obj = create_obj.unwrap();
                    let write_result = f_obj.write_all(&buffer);
                    if write_result.is_err() {
                        split_error = true;
                        break;
                    } else {
                        let zip_file_name =
                            self.compress_file(tmp_file_name.clone(), String::new());
                        if zip_file_name.len() > 0 {
                            self.result_list.push(zip_file_name.clone());
                            let path = PathBuf::from(&zip_file_name.clone());
                            let filename = path.file_name().unwrap();
                            let file_name_str = String::from(filename.to_str().unwrap());
                            let chunk_hash = self.calculate_file_hash(zip_file_name.clone());
                            _ = fs::remove_file(tmp_file_name.clone());
                            file_hash_list
                                .insert(counter, (chunk_hash, String::from(file_name_str.clone().substring(0, file_name_str.len() - 4))));
                        } else {
                            split_error = true;
                            break;
                        }
                    }
                } else {
                    split_error = true;
                    break;
                }
                reader.consume(buffer_length);
            } else {
                split_error = true;
                break;
            }
            counter = counter + 1;
        }
        self.result_obj = FileChunkSplitResult {
            info_file: String::new(),
            file_name: String::new(),
            file_hash: String::new(),
            file_size: 0,
            chunk_size: 0,
            chunk_count: 0,
            list: HashMap::new(),
        };
        if split_error == false {
            self.result_obj.file_name = std::path::Path::new(&self.file_name)
                .file_name()
                .unwrap()
                .to_str()
                .unwrap()
                .to_string();
            self.result_obj.file_hash = self.file_hash.clone();
            self.result_obj.file_size = self.file_size as usize;
            self.result_obj.chunk_size = self.chunk_size() as usize;
            self.result_obj.chunk_count = counter - 1;
            self.result_obj.list = file_hash_list.clone();
            let mut tmp_file_name = tmp_chunk_dir.clone();
            tmp_file_name.push(std::path::MAIN_SEPARATOR);
            tmp_file_name.push_str("info.json");
            self.result_obj.info_file = tmp_file_name.clone();
            let create_obj = std::fs::File::create(tmp_file_name.clone());
            if create_obj.is_ok() {
                let mut f_obj = create_obj.unwrap();
                let info_json_obj = json!({
                    "info_file":self.result_obj.info_file,
                    "file_name":self.result_obj.file_name,
                    "file_hash":self.result_obj.file_hash,
                    "file_size":self.result_obj.file_size,
                    "chunk_size":self.result_obj.chunk_size,
                    "chunk_count":self.result_obj.chunk_count,
                    "list":self.result_obj.list
                });
                let tmp_result_str = serde_json::to_string_pretty(&info_json_obj).unwrap();
                let tmp_write_result = f_obj.write_all(&tmp_result_str.clone().as_bytes());
                if tmp_write_result.is_ok() {
                    let zip_file_name = self.compress_file(tmp_file_name.clone(), self.result_obj.file_hash.clone());
                    _ = fs::remove_file(tmp_file_name.clone());
                    return (true, zip_file_name.clone());
                }
            }
        }
        let _remove_result = fs::remove_dir_all(clear_folder_name);
        return (false, String::new());
    }
    fn compress_file(&self, raw_file_name: String, zip_name: String) -> String {
        let path = PathBuf::from(&raw_file_name.clone());
        let dir = path.parent().unwrap();
        let zip_raw_name = if zip_name.len() == 0 {
            self.get_time(24).to_string()
        } else {
            zip_name.clone()
        };
        let zip_file_name = format!(
            "{}{}{}.zip",
            dir.to_str().unwrap(),
            std::path::MAIN_SEPARATOR,
            zip_raw_name
        );
        let file = File::create(zip_file_name.clone());
        if file.is_err() {
            return String::new();
        }
        let mut zip = ZipWriter::new(file.unwrap());
        let ss1 = zip.start_file("raw.data", FileOptions::default());
        if ss1.is_err() {
            return String::new();
        }
        let f = File::open(raw_file_name.clone());
        if f.is_err() {
            return String::new();
        }

        let mut inner_buffer = Vec::new();
        let mut f_inner = f.unwrap();
        let rst = f_inner.read_to_end(&mut inner_buffer);
        if rst.is_err() {
            return String::new();
        }
        let ss2 = zip.write_all(&inner_buffer);
        if ss2.is_err() {
            return String::new();
        }
        let ss3 = zip.finish();
        if ss3.is_err() {
            return String::new();
        }
        return zip_file_name.clone();
    }
    pub fn result(&self) -> FileChunkSplitResult {
        self.result_obj.clone()
    }
    fn get_time(&self,fixed_length:usize) -> u128 {
        let start = SystemTime::now();
        let since_the_epoch = start
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards");
        if fixed_length==0{
            since_the_epoch.as_millis()
        }else{
            let mut rng = rand::thread_rng();
            let mut time_str=since_the_epoch.as_millis().to_string();
            loop{
                let result=rng.gen::<u64>().to_string().chars().nth(1).unwrap();
                time_str.push(result);
                if fixed_length==time_str.len(){
                    break;
                }
            }
            time_str.parse::<u128>().unwrap()
        }
    }
    fn change_file_name(&self, full_path: &str, new_filename: &str) -> String {
        let mut store_path = Path::new(full_path).to_owned();
        store_path.set_file_name(new_filename);
        store_path.display().to_string()
    }
    fn read_from_zip_file(&self, zip_filename: &str) -> String {
        let storage_filename = self.change_file_name(zip_filename.clone(), "raw.data");
        let path = Path::new(zip_filename.clone());
        let file = File::open(&path);
        if file.is_err() {
            return "".to_string();
        }
        let file = file.unwrap();
        let archive = ZipArchive::new(file);
        if archive.is_err() {
            return "".to_string();
        }
        let mut archive = archive.unwrap();
        for i in 0..archive.len() {
            let file = archive.by_index(i);
            if file.is_err() {
                return "".to_string();
            }
            let mut file = file.unwrap();
            if file.name().eq("raw.data") {
                let mut buffer = Vec::new();
                let rst = file.read_to_end(&mut buffer);
                if rst.is_err() {
                    return "".to_string();
                }
                let save_result = fs::write(storage_filename.clone(), buffer);
                if save_result.is_ok() {
                    return storage_filename;
                }
                return "".to_string();
            }
        }
        return "".to_string();
    }
    pub fn merge(&self, info_file_path: &str) -> bool {
        let raw_data_file_name = self.change_file_name(&info_file_path.clone(), "raw.data");
        let info_filename = self.read_from_zip_file(info_file_path);
        let contents = fs::read_to_string(info_filename.clone());
        if contents.is_err() {
            return false;
        }
        let file_contents = contents.unwrap();
        let info_obj: FileChunkSplitResult = serde_json::from_str(&file_contents).unwrap();

        let output_file_name = self.change_file_name(&info_filename.clone(), &info_obj.file_name.clone());
        if output_file_name.len()>0{
            let output_file_obj = std::fs::File::create(output_file_name.clone());
            if output_file_obj.is_err() {
                return false;
            }
            let mut output_file_obj = output_file_obj.unwrap();
            for count in 1..info_obj.chunk_count + 1 {
                let item = info_obj.list.get(&count);
                if item.is_none() {
                    _ = fs::remove_file(raw_data_file_name.clone());
                    return false;
                }
                let (chunk_hash, chunk_filename) = item.unwrap();
                let zip_filename = self.change_file_name(
                    info_file_path.clone(),
                    &format!("{}.zip", chunk_filename.clone()),
                );
                let file_meta = fs::metadata(zip_filename.clone());
                if file_meta.is_err() {
                    _ = fs::remove_file(raw_data_file_name.clone());
                    return false;
                }
                if info_obj.list.contains_key(&count) == false {
                    _ = fs::remove_file(raw_data_file_name.clone());
                    return false;
                }
                let chunk_file_hash = self.calculate_file_hash(zip_filename.clone().to_string());
                if chunk_hash.eq(&chunk_file_hash.clone()) == false {
                    _ = fs::remove_file(raw_data_file_name.clone());
                    return false;
                }
                let chunk_filename = self.read_from_zip_file(&zip_filename.clone());
                if chunk_filename.len()>0{
                    let bytes_buf = fs::read(chunk_filename.clone()).unwrap();
                    let write_result = output_file_obj.write_all(&bytes_buf);
                    if write_result.is_err() {
                        _ = fs::remove_file(raw_data_file_name.clone());
                        return false;
                    }
                }
            }        
        }
        _ = fs::remove_file(raw_data_file_name.clone());
        let calculated_file_hash = self.calculate_file_hash(output_file_name.clone().to_string());
        if info_obj.file_hash.eq(&calculated_file_hash.clone()) == false {
            return false;
        }
        return true;
    }
}

#[test]
fn full_test() {
    // cargo test  --lib full_test -- --nocapture
    fn generate_tmp_file(file_size: usize) -> String {
        let mut result_str = String::new();
        #[cfg(windows)]
        const LINE_ENDING: &str = "\r\n";
        #[cfg(not(windows))]
        const LINE_ENDING: &str = "\n";
        let mut counter = 1;
        loop {
            let micros_time = std::time::SystemTime::now()
                .duration_since(std::time::SystemTime::UNIX_EPOCH)
                .unwrap()
                .as_micros();
            result_str.push_str("Lorem Ipsum Text Line => ");
            result_str.push_str(&counter.to_string());
            result_str.push_str(" => ");
            result_str.push_str(&micros_time.to_string());
            result_str.push_str(LINE_ENDING);
            counter = counter + 1;
            if result_str.len() > file_size {
                break;
            }
        }
        let hash_file_name = format!("{}", blake3::hash(&result_str.clone().as_bytes()).to_hex());
        let mut tmp_file_name = format!("{}", std::env::temp_dir().to_str().unwrap());
        tmp_file_name.push_str(&hash_file_name);
        tmp_file_name.push_str(".txt");

        let create_obj = std::fs::File::create(tmp_file_name.clone());
        if create_obj.is_ok() {
            let mut f_obj = create_obj.unwrap();
            let write_result = f_obj.write_all(&result_str.as_bytes());
            if write_result.is_ok() {
                return tmp_file_name;
            }
        }
        return String::new();
    }
    let mut error_status = true;
    let file_name = generate_tmp_file(1000000);
    let mut file_obj = FileChunk::new();
    file_obj.set_storage_path(DefaultStoragePath::TempPath);
    file_obj.assign_file(&file_name.clone());
    if file_obj.is_exist == true {
        file_obj.set_size(256, FileChunkType::KiloByte);
        let (split_result, _archive_name) = file_obj.split();
        if split_result == true {
            let _result_json = file_obj.result();
            let merge_result = file_obj.merge(&_result_json.info_file);
            if merge_result == true {
                error_status = false;
            }

            //dizin icindeki gecici dosyalar siliniyor...
            let path = Path::new(&_result_json.info_file);
            let mut base_path = path.parent().unwrap().display().to_string();
            base_path.push(std::path::MAIN_SEPARATOR);
            for file in fs::read_dir(base_path).unwrap() {
                let clear_file_name = file.unwrap().path().display().to_string();
                _ = fs::remove_file(clear_file_name.clone());
            }
        }
    }
    // olusturulan temp dosyasi siliniyor
    _ = fs::remove_file(file_name.clone());
    if error_status == true {
        assert_eq!(true, false)
    } else {
        assert_eq!(true, true)
    }
}