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
use crate::{
    cli::{actions::Action, globals::GlobalArgs, progressbar::Bar},
    s3::{actions, S3},
};
use anyhow::{anyhow, Context, Result};
use colored::Colorize;
use std::{
    cmp::min,
    ffi::OsStr,
    path::{Path, PathBuf},
};
use tokio::{
    fs::OpenOptions,
    io::AsyncWriteExt,
    time::{sleep, Duration},
};

/// # Errors
/// Will return an error if the action fails
pub async fn handle(s3: &S3, action: Action, globals: GlobalArgs) -> Result<()> {
    if let Action::GetObject {
        key,
        metadata,
        dest,
        quiet,
        force,
    } = action
    {
        if metadata {
            let action = actions::HeadObject::new(&key);
            let headers = action.request(s3).await?;

            let mut i = 0;

            for k in headers.keys() {
                i = k.len();
            }

            i += 1;
            for (k, v) in headers {
                println!("{:<width$} {}", format!("{k}:").green(), v, width = i);
            }
        } else {
            let file_name = Path::new(&key)
                .file_name()
                .with_context(|| format!("Failed to get file name from: {key}"))?;

            let path = get_dest(dest, file_name)?;

            // check if file exists
            if path.is_file() && !force {
                return Err(anyhow!("file {:?} already exists", path));
            }

            // open
            let mut options = OpenOptions::new();
            options.write(true).create(true);

            // Set truncate flag to overwrite the file if it exists
            if force {
                options.truncate(true);
            }

            // do the request
            let action = actions::GetObject::new(&key);
            let mut res = action.request(s3, &globals).await?;

            // Open the file with the specified options
            let mut file = options
                .open(&path)
                .await
                .context(format!("could not open {}", &path.display()))?;

            // get the file_size in bytes by using the content_length
            let file_size = res
                .content_length()
                .context("could not get content_length")?;

            // if quiet is true, then use a default progress bar
            let pb = Bar::new(file_size, Some(quiet));

            let mut downloaded = 0;
            while let Some(bytes) = res.chunk().await? {
                let new = min(downloaded + bytes.len() as u64, file_size);

                downloaded = new;

                if let Some(pb) = pb.progress.as_ref() {
                    pb.set_position(new);
                }

                file.write_all(&bytes).await?;

                // throttle bandwidth
                if let Some(bandwidth_kb) = globals.throttle {
                    throttle_download(bandwidth_kb, bytes.len()).await;
                }
            }

            if let Some(pb) = pb.progress.as_ref() {
                pb.finish();
            }

            while let Some(bytes) = res.chunk().await? {
                file.write_all(&bytes).await?;
            }
        }
    }

    Ok(())
}

async fn throttle_download(bandwidth_kb: usize, chunk_size: usize) {
    let bandwidth_bytes_per_sec = bandwidth_kb * 1024;

    let duration_per_chunk =
        Duration::from_secs(chunk_size as u64 / bandwidth_bytes_per_sec as u64);

    sleep(duration_per_chunk).await;

    log::info!(
        "Throttling to {} KB/s (duration per chunk: {}, chunk size: {})",
        bandwidth_kb,
        duration_per_chunk.as_secs_f64(),
        chunk_size
    );
}

fn get_dest(dest: Option<String>, file_name: &OsStr) -> Result<PathBuf> {
    if let Some(d) = dest {
        let mut path_buf = PathBuf::from(&d);

        // Check if the provided path is a directory
        if path_buf.is_dir() {
            path_buf.push(file_name);
            return Ok(path_buf);
        }

        // If it's a file, check if the parent directory exists
        if let Some(parent) = path_buf.parent() {
            if parent.exists() {
                return Ok(path_buf);
            } else if path_buf.components().count() > 1 {
                return Err(anyhow!(
                    "parent directory {} does not exist",
                    parent.display()
                ));
            }
            return Ok(Path::new(".").join(path_buf));
        }
    }

    // Use default path if dest is None
    Ok(Path::new(".").join(file_name))
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::Result;

    struct Test {
        dest: Option<String>,
        file_name: &'static OsStr,
        expected: Option<PathBuf>,
        error_expected: bool,
    }

    #[tokio::test]
    async fn test_get_dest() -> Result<()> {
        let tests = vec![
            Test {
                dest: None,
                file_name: &OsStr::new("key.json"),
                expected: Some(Path::new(".").join("key.json")),
                error_expected: false,
            },
            Test {
                dest: Some("./file.txt".to_string()),
                file_name: &OsStr::new("key.json"),
                expected: Some(Path::new(".").join("file.txt")),
                error_expected: false,
            },
            Test {
                dest: Some(".".to_string()),
                file_name: &OsStr::new("key.json"),
                expected: Some(Path::new(".").join("key.json")),
                error_expected: false,
            },
            Test {
                dest: Some("file.txt".to_string()),
                file_name: &OsStr::new("key.json"),
                expected: Some(Path::new(".").join("file.txt")),
                error_expected: false,
            },
            Test {
                dest: Some("/file.txt".to_string()),
                file_name: &OsStr::new("key.json"),
                expected: Some(Path::new("/").join("file.txt")),
                error_expected: false,
            },
            Test {
                dest: Some("tmp/file.txt".to_string()),
                file_name: &OsStr::new("key.json"),
                expected: None,
                error_expected: true,
            },
            Test {
                dest: Some("a/b/cfile.txt".to_string()),
                file_name: &OsStr::new("key.json"),
                expected: None,
                error_expected: true,
            },
        ];

        for test in tests {
            match get_dest(test.dest, test.file_name) {
                Ok(res) => {
                    if test.error_expected {
                        // If an error was not expected but the test passed, fail the test
                        panic!("Expected an error, but got: {:?}", res);
                    } else {
                        assert_eq!(res, test.expected.unwrap());
                    }
                }
                Err(_) => {
                    if !test.error_expected {
                        // If an error was not expected but the test failed, fail the test
                        panic!("Unexpected error");
                    }
                }
            }
        }

        Ok(())
    }
}