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
use std::{
    cmp::Ordering,
    fmt::Display,
    path::PathBuf,
    sync::{atomic::AtomicU64, Arc},
};

use checksum::Checksum;
use derive_builder::Builder;
use download::SingleDownloaderBuilder;
use futures::StreamExt;

use reqwest::Client;

pub mod checksum;
mod download;

pub use reqwest;

#[derive(thiserror::Error, Debug)]
pub enum DownloadError {
    #[error("checksum mismatch {0}")]
    ChecksumMisMatch(String),
    #[error("Failed to download file: {0}, kind: {1}")]
    IOError(String, std::io::Error),
    #[error(transparent)]
    ReqwestError(reqwest::Error),
    #[error(transparent)]
    ChecksumError(#[from] crate::checksum::ChecksumError),
    #[error("Failed to open local source file {0}: {1}")]
    FailedOpenLocalSourceFile(String, tokio::io::Error),
    #[error(transparent)]
    DownloadSourceBuilderError(#[from] DownloadEntryBuilderError),
    #[error("Invaild URL: {0}")]
    InvaildURL(String),
    #[error("download source list is empty")]
    EmptySources,
}

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

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

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum CompressFile {
    Bz2,
    Gzip,
    Xz,
    Zstd,
    #[default]
    Nothing,
}

impl Ord for CompressFile {
    fn cmp(&self, other: &Self) -> Ordering {
        match self {
            CompressFile::Bz2 => match other {
                CompressFile::Bz2 => Ordering::Equal,
                CompressFile::Gzip => Ordering::Less,
                CompressFile::Xz => Ordering::Less,
                CompressFile::Zstd => Ordering::Less,
                CompressFile::Nothing => Ordering::Greater,
            },
            CompressFile::Gzip => match other {
                CompressFile::Bz2 => Ordering::Greater,
                CompressFile::Gzip => Ordering::Less,
                CompressFile::Xz => Ordering::Less,
                CompressFile::Zstd => Ordering::Less,
                CompressFile::Nothing => Ordering::Greater,
            },
            CompressFile::Xz => match other {
                CompressFile::Bz2 => Ordering::Greater,
                CompressFile::Gzip => Ordering::Greater,
                CompressFile::Xz => Ordering::Equal,
                CompressFile::Zstd => Ordering::Less,
                CompressFile::Nothing => Ordering::Greater,
            },
            CompressFile::Zstd => match other {
                CompressFile::Bz2 => Ordering::Greater,
                CompressFile::Gzip => Ordering::Greater,
                CompressFile::Xz => Ordering::Greater,
                CompressFile::Zstd => Ordering::Equal,
                CompressFile::Nothing => Ordering::Greater,
            },
            CompressFile::Nothing => match other {
                CompressFile::Bz2 => Ordering::Less,
                CompressFile::Gzip => Ordering::Less,
                CompressFile::Xz => Ordering::Less,
                CompressFile::Zstd => Ordering::Less,
                CompressFile::Nothing => Ordering::Equal,
            },
        }
    }
}

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

impl From<&str> for CompressFile {
    fn from(s: &str) -> Self {
        match s {
            "xz" => CompressFile::Xz,
            "gz" => CompressFile::Gzip,
            "bz2" => CompressFile::Bz2,
            "zst" => CompressFile::Zstd,
            _ => CompressFile::Nothing,
        }
    }
}

#[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 { as_symlink: bool },
}

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

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

pub struct OmaFetcher<'a> {
    client: &'a Client,
    download_list: Vec<DownloadEntry>,
    limit_thread: usize,
    retry_times: usize,
    global_progress: Arc<AtomicU64>,
}

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

#[derive(Debug)]
pub enum DownloadEvent {
    ChecksumMismatchRetry { filename: String, times: usize },
    GlobalProgressSet(u64),
    GlobalProgressInc(u64),
    ProgressDone,
    NewProgressSpinner(String),
    NewProgress(u64, String),
    ProgressInc(u64),
    ProgressSet(u64),
    CanNotGetSourceNextUrl(String),
    Done(String),
    AllDone,
}

impl Display for DownloadEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{self:?}"))
    }
}

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

/// OmaFetcher is a Download Manager
impl<'a> OmaFetcher<'a> {
    pub fn new(
        client: &'a Client,
        download_list: Vec<DownloadEntry>,
        limit_thread: Option<usize>,
    ) -> DownloadResult<OmaFetcher<'a>> {
        Ok(Self {
            client,
            download_list,
            limit_thread: limit_thread.unwrap_or(4),
            retry_times: 3,
            global_progress: Arc::new(AtomicU64::new(0)),
        })
    }

    /// 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<F>(&self, callback: F) -> Vec<DownloadResult<Summary>>
    where
        F: Fn(usize, DownloadEvent) + Clone + Send + Sync,
    {
        let callback = Arc::new(callback);
        let mut tasks = Vec::new();
        let mut list = vec![];
        for (i, c) in self.download_list.iter().enumerate() {
            let msg = Arc::new(c.msg.clone());
            // 因为数据的来源是确定的,所以这里能够确定肯定不崩溃,因此直接 unwrap
            let single = SingleDownloaderBuilder::default()
                .client(self.client)
                .context(msg.clone())
                .download_list_index(i)
                .entry(c)
                .progress((i + 1, self.download_list.len(), msg))
                .retry_times(self.retry_times)
                .file_type(c.file_type.clone())
                .build()
                .unwrap();

            list.push(single);
        }

        let file_download_source = list
            .iter()
            .filter(|x| {
                x.entry
                    .source
                    .iter()
                    .any(|x| matches!(x.source_type, DownloadSourceType::Local { .. }))
            })
            .count();

        let http_download_source = list.len() - file_download_source;

        for single in list {
            tasks.push(single.try_download(self.global_progress.clone(), callback.clone()));
        }

        let thread = if file_download_source >= http_download_source {
            1
        } else {
            self.limit_thread
        };

        let stream = futures::stream::iter(tasks).buffer_unordered(thread);
        let res = stream.collect::<Vec<_>>().await;
        callback(0, DownloadEvent::AllDone);

        res
    }
}