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
use std::{path::PathBuf, sync::Arc};

use derive_builder::Builder;
use futures::StreamExt;
use oma_console::{
    indicatif::{self, MultiProgress, ProgressBar},
    writer::Writer,
};

use reqwest::{Client, ClientBuilder};

pub mod checksum;
mod download;

use download::try_download;

#[derive(thiserror::Error, Debug)]
pub enum DownloadError {
    #[error("checksum mismatch {0} at dir {1}")]
    ChecksumMisMatch(String, String),
    #[error("404 not found: {0}")]
    NotFound(String),
    #[error(transparent)]
    IOError(#[from] tokio::io::Error),
    #[error(transparent)]
    ReqwestError(#[from] reqwest::Error),
    #[error(transparent)]
    ChecksumError(#[from] crate::checksum::ChecksumError),
    #[error(transparent)]
    TemplateError(#[from] indicatif::style::TemplateError),
    #[error("Failed to open local source file {0}: {1}")]
    FailedOpenLocalSourceFile(String, String),
    #[error("Download all file failed: {0}: {1}")]
    DownloadAllFailed(String, String),
    #[error(transparent)]
    DownloadSourceBuilderError(#[from] DownloadEntryBuilderError),
    #[error("Invaild URL: {0}")]
    InvaildURL(String),
}

pub type DownloadResult<T> = std::result::Result<T, DownloadError>;

#[derive(Debug, Clone, Builder, Default)]
#[builder(default)]
pub struct DownloadEntry {
    source: Vec<DownloadSource>,
    filename: String,
    dir: PathBuf,
    #[builder(setter(into, strip_option))]
    hash: Option<String>,
    allow_resume: bool,
    #[builder(setter(into, strip_option))]
    msg: Option<String>,
    extract: bool,
}

#[derive(Debug, Clone)]
pub struct DownloadSource {
    url: String,
    source_type: DownloadSourceType,
}

impl DownloadSource {
    pub fn new(url: String, source_type: DownloadSourceType) -> Self {
        Self { url, source_type }
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum DownloadSourceType {
    Http,
    Local,
}

impl PartialOrd for DownloadSourceType {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for DownloadSourceType {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        match self {
            DownloadSourceType::Http => match other {
                DownloadSourceType::Http => std::cmp::Ordering::Equal,
                DownloadSourceType::Local => std::cmp::Ordering::Less,
            },
            DownloadSourceType::Local => match other {
                DownloadSourceType::Http => std::cmp::Ordering::Greater,
                DownloadSourceType::Local => std::cmp::Ordering::Equal,
            },
        }
    }
}

#[derive(Clone)]
pub struct FetchProgressBar {
    pub mb: Arc<MultiProgress>,
    pub global_bar: Option<ProgressBar>,
    pub progress: Option<(usize, usize)>,
    pub msg: Option<String>,
}

impl FetchProgressBar {
    pub fn new(
        mb: Arc<MultiProgress>,
        global_bar: Option<ProgressBar>,
        progress: Option<(usize, usize)>,
        msg: Option<String>,
    ) -> Self {
        Self {
            mb,
            global_bar,
            progress,
            msg,
        }
    }
}

pub struct OmaFetcher {
    client: Client,
    bar: Option<(Arc<MultiProgress>, Option<ProgressBar>)>,
    download_list: Vec<DownloadEntry>,
    limit_thread: usize,
    retry_times: usize,
}

#[derive(Debug)]
pub struct Summary {
    pub filename: String,
    pub writed: bool,
    pub count: usize,
    pub context: Option<String>,
}

/// Summary struct to save download result
impl Summary {
    fn new(filename: &str, writed: bool, count: usize, context: Option<String>) -> Self {
        Self {
            filename: filename.to_string(),
            writed,
            count,
            context,
        }
    }
}

/// OmaFetcher is a Download Manager
impl OmaFetcher {
    pub fn new(
        client: Option<Client>,
        bar: bool,
        total_size: Option<u64>,
        download_list: Vec<DownloadEntry>,
        limit_thread: Option<usize>,
    ) -> DownloadResult<Self> {
        let client = client.unwrap_or(ClientBuilder::new().user_agent("oma").build()?);

        let bar = if bar {
            let mb = Arc::new(MultiProgress::new());
            let writer = Writer::default();
            let gpb = if let Some(total_size) = total_size {
                Some(
                    mb.insert(
                        0,
                        ProgressBar::new(total_size)
                            .with_style(oma_console::pb::oma_style_pb(writer, true)?),
                    ),
                )
            } else {
                None
            };

            if let Some(ref gpb) = gpb {
                gpb.set_message("Progress")
            }

            Some((mb, gpb))
        } else {
            None
        };

        Ok(Self {
            client,
            bar,
            download_list,
            limit_thread: limit_thread.unwrap_or(4),
            retry_times: 3,
        })
    }

    /// Set retry times
    pub fn retry_times(&mut self, retry_times: usize) -> &mut Self {
        self.retry_times = retry_times;
        self
    }

    /// Start download
    pub async fn start_download(&self) -> Vec<DownloadResult<Summary>> {
        let mut tasks = Vec::new();
        for (i, c) in self.download_list.iter().enumerate() {
            let fpb = if let Some((mb, gpb)) = &self.bar {
                Some(FetchProgressBar {
                    mb: mb.clone(),
                    global_bar: gpb.clone(),
                    progress: Some((i + 1, self.download_list.len())),
                    msg: c.msg.clone(),
                })
            } else {
                None
            };

            tasks.push(try_download(
                &self.client,
                c,
                fpb,
                i,
                self.retry_times,
                c.msg.clone(),
            ));
        }

        let stream = futures::stream::iter(tasks).buffer_unordered(self.limit_thread);

        let res = stream.collect::<Vec<_>>().await;

        if let Some(gpb) = self.bar.as_ref().and_then(|x| x.1.as_ref()) {
            gpb.finish_and_clear();
        }

        res
    }
}