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
use crate::error::{DownloadError, DownloadResult};
use futures::{stream, StreamExt, TryStreamExt};
use sha1::Digest;
use sha1::Sha1;
use std::cmp::min;
use std::path::PathBuf;
use tokio::fs::create_dir_all;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use tokio::sync::mpsc::channel;
use tokio::sync::mpsc::Receiver;
use tokio::sync::mpsc::Sender;
use tokio::task;

#[derive(Clone, Debug)]
pub struct Download {
    pub url: String,
    pub file: PathBuf,
    pub sha1: Option<Vec<u8>>,
}

impl Download {
    #[instrument(
        name = "download_file",
        level = "trace",
        skip_all,
        fields(
            url = self.url,
            file = %self.file.to_string_lossy(),
            current_file,
            total_files,
        )
    )]
    pub async fn download(
        &self,
        client: reqwest::Client,
        mut progress_sender: Option<Sender<DownloadProgress>>,
        current_file: usize,
        total_files: usize,
    ) -> DownloadResult<()> {
        // Create parent folder
        if let Some(parent) = self.file.parent() {
            trace!("Creating parent folder");
            create_dir_all(parent).await?;
        }

        // Setup request
        let response = client.get(&self.url).send().await?.error_for_status()?;

        // Progress Update
        trace!("Sending request to get content-length");
        let total_bytes = response
            .content_length()
            .ok_or(DownloadError::NoContentLength)?;
        let mut progress = DownloadProgress {
            url: self.url.clone(),
            file: self.file.clone(),
            current_file,
            total_files,
            downloaded_bytes: 0,
            total_bytes,
        };

        trace!("Send initial progress");
        progress.send(&mut progress_sender).await;

        let mut file = File::create(&self.file).await?;
        let mut stream = response.bytes_stream();

        trace!("Writing content to disk.");
        while let Some(item) = stream.next().await {
            let chunk = item?;
            file.write_all(&chunk).await?;
            progress.downloaded_bytes = min(
                progress.downloaded_bytes + (chunk.len() as u64),
                progress.total_bytes,
            );

            trace!("Send progress");
            progress.send(&mut progress_sender).await;
        }

        file.sync_all().await?;

        Ok(())
    }

    #[instrument(
        name = "verify_file",
        level = "trace",
        skip_all,
        fields(
            url = self.url,
            file = %self.file.to_string_lossy(),
        )
    )]
    pub async fn verify(&self) -> DownloadResult<bool> {
        let this = self.clone();

        task::spawn_blocking(move || this.blocking_verify())
            .await
            .unwrap()
    }

    fn blocking_verify(self) -> DownloadResult<bool> {
        if let Some(sha) = self.sha1 {
            if !self.file.is_file() {
                return Ok(false);
            }

            let mut file = std::fs::File::open(self.file)?;
            let mut hasher = Sha1::new();
            std::io::copy(&mut file, &mut hasher)?;
            let hash = hasher.finalize().to_vec();

            Ok(sha == hash)
        } else {
            Ok(self.file.is_file())
        }
    }
}

/// Progress of an ongoing download.
#[derive(Clone, Debug)]
pub struct DownloadProgress {
    /// The URL of the download.
    pub url: String,
    /// The path where the file is saved.
    pub file: PathBuf,
    /// Current file index.
    pub current_file: usize,
    /// Number of files that are being downloaded.
    pub total_files: usize,
    /// Bytes that already got downloaded.
    pub downloaded_bytes: u64,
    /// Total bytes of the file.
    pub total_bytes: u64,
}

impl DownloadProgress {
    pub(crate) async fn send(&self, sender: &mut Option<Sender<Self>>) {
        if let Some(s) = &sender {
            if s.send(self.clone()).await.is_err() {
                trace!("Sending failed because receiver is no longer around. Dropping sender...");
                *sender = None;
            }
        }
    }
}

#[instrument(
    name = "download",
    level = "trace",
    skip_all,
    fields(parallel_downloads, verify)
)]
pub async fn download(
    downloads: Vec<Download>,
    progress_sender: Option<Sender<DownloadProgress>>,
    parallel_downloads: u16,
    retries: u16,
    verify: bool,
) -> DownloadResult<()> {
    let client = reqwest::Client::new();
    let total = downloads.len();
    let downloads = downloads.into_iter().enumerate();

    stream::iter(downloads)
        .map(move |(n, d)| {
            let client = client.clone();
            let mut sender = progress_sender.clone();
            async move {
                // Retries
                for x in 0..=retries {
                    if x > 0 {
                        trace!("Retrying to download file for the {}th time", x);
                    }

                    // Download file
                    if !d.file.exists() || x > 0 {
                        trace!("File does not exist or retrying");
                        d.download(client.clone(), sender.clone(), n, total).await?;
                    } else {
                        trace!("File does exist, sending progress update");
                        let file = File::open(&d.file).await?;
                        let size = file.metadata().await?.len();

                        // Send progress
                        DownloadProgress {
                            url: d.url.clone(),
                            file: d.file.clone(),
                            current_file: n,
                            total_files: total,
                            downloaded_bytes: size,
                            total_bytes: size,
                        }
                        .send(&mut sender)
                        .await;
                    }

                    // Verify file
                    if verify && !d.verify().await? {
                        // Checksum does not match
                        if x == retries {
                            debug!("Verification of file failed");
                            return Err(DownloadError::ChecksumMismatch);
                        } else {
                            debug!("Verification of file failed, retrying...");
                        }
                    } else {
                        // Success
                        return Ok(());
                    }
                }

                Ok(())
            }
        })
        .buffer_unordered(parallel_downloads as usize)
        .try_collect::<()>()
        .await?;

    Ok(())
}

pub fn download_progress_channel(
    buffer: usize,
) -> (Sender<DownloadProgress>, Receiver<DownloadProgress>) {
    channel(buffer)
}