downloader_rs/
download_operation.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
use std::sync::{Arc};
use crate::download_status::DownloadStatus;
use crate::download_receiver::DownloadReceiver;
use crate::downloader::{Downloader};
use crate::error::DownloadError;

pub struct DownloadOperation {
    downloader: Arc<Downloader>,
    download_receiver: DownloadReceiver,
}

impl DownloadOperation {
    pub fn new(
        downloader: Arc<Downloader>,
        download_receiver: DownloadReceiver) -> DownloadOperation {
        DownloadOperation {
            downloader,
            download_receiver,
        }
    }

    pub fn status(&self) -> DownloadStatus {
        let status = self.downloader.status();
        return status;
    }

    pub fn downloaded_size(&self) -> u64 {
        return *self.download_receiver.downloaded_size_receiver.borrow();
    }

    pub fn total_size(&self) -> u64 {
        return *self.download_receiver.download_total_size_receiver.borrow();
    }

    pub fn progress(&self) -> f64 {
        let total_size = self.total_size();
        if total_size == 0 {
            return 0f64;
        }
        let total_length = total_size as f64;
        let downloaded_size = self.downloaded_size() as f64;
        return (downloaded_size / total_length).clamp(0f64, 1f64);
    }

    pub fn bytes(&self) -> Vec<u8> {
        let bytes = self.download_receiver.memory_receiver.as_ref().unwrap().borrow();
        bytes.to_vec()
    }

    pub fn is_done(&self) -> bool {
        return self.downloader.is_done();
    }

    pub fn is_error(&self) -> bool {
        return self.status() == DownloadStatus::Failed;
    }

    pub fn error(&self) -> DownloadError {
        return (*self.download_receiver.error_receiver.borrow()).clone();
    }

    pub fn stop(&self) {
        self.downloader.stop();
    }
}