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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
//! Download assets.

use crate::{Error, Result};
use async_trait::async_trait;
use reqwest::Client;
use serde::Serialize;
use stac::{Asset, Assets, Collection, Href, Item, Link, Links, Value};
use std::path::{Path, PathBuf};
use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc::Sender, task::JoinSet};
use url::Url;

const DEFAULT_FILE_NAME: &str = "download.json";
const DEFAULT_WRITE_STAC: bool = true;
const DEFAULT_CREATE_DIRECTORY: bool = true;

/// Downloads all assets from a [Item](stac::Item) or [Collection](stac::Collection).
///
/// The STAC object's self href and asset hrefs are updated to point to the
/// downloaded locations. The original object's locations is included in a
/// "canonical" link.
///
/// # Examples
///
/// ```no_run
/// # tokio_test::block_on(async {
/// let value = stac_async::download("data/simple-item.json", "outdir").await.unwrap();
/// # })
/// ```
pub async fn download(href: impl ToString, directory: impl AsRef<Path>) -> Result<Value> {
    let value = crate::read(href).await?;
    match value {
        Value::Item(item) => item.download(directory).await.map(|item| Value::Item(item)),
        Value::Collection(collection) => collection
            .download(directory)
            .await
            .map(|collection| Value::Collection(collection)),
        _ => Err(Error::CannotDownload(value)),
    }
}

/// Download the assets from anything that implements [Assets].
#[async_trait(?Send)]
pub trait Download: Assets + Links + Href + Serialize + Clone {
    /// Download the assets, and the object itself, to a directory on the local filesystem.
    ///
    /// # Examples
    ///
    /// [Item] implements [Download]:
    ///
    /// ```no_run
    /// use stac::{Item, Links};
    /// use stac_async::Download;
    ///
    /// let item: Item = stac::read("data/simple-item.json").unwrap();
    /// # tokio_test::block_on(async {
    /// let downloaded_item = item.download("outdir").await.unwrap();
    /// # })
    /// ```
    async fn download(self, directory: impl AsRef<Path>) -> Result<Self>
    where
        Self: Sized,
    {
        Downloader::new(self)?.download(directory).await
    }
}

/// A customizable download structure.
#[derive(Debug)]
pub struct Downloader<T: Links + Assets + Href + Serialize + Clone> {
    stac: T,
    client: Client,
    file_name: String,
    create_directory: bool,
    sender: Option<Sender<Message>>,
    write_stac: bool,
}

/// A message from a downloader.
#[derive(Debug)]
pub enum Message {
    /// Create a download directory.
    CreateDirectory(PathBuf),

    /// Send a GET request for an asset.
    GetAsset {
        /// The asset downloader id.
        id: usize,

        /// The url of the asset.
        url: Url,
    },

    /// Got a successful asset response.
    GotAsset {
        /// The asset downloader id.
        id: usize,

        /// The length of the asset response.
        content_length: Option<u64>,
    },

    /// Update the number of bytes written.
    Update {
        /// The asset downloader id.
        id: usize,

        /// Then umber of bytes written.
        bytes_written: usize,
    },

    /// The download is finished.
    FinishedDownload(usize),

    /// All downloads are finished.
    FinishedAllDownloads,

    /// Write the stac file to the local filesystem.
    WriteStac(PathBuf),
}

#[derive(Debug)]
struct AssetDownloader {
    id: usize,
    key: String,
    asset: Asset,
    client: Client,
    sender: Option<Sender<Message>>,
}

impl<T: Links + Assets + Href + Serialize + Clone> Downloader<T> {
    /// Creates a new downloader.
    ///
    /// # Examples
    ///
    /// ```
    /// let item: stac::Item = stac::read("data/simple-item.json").unwrap();
    /// let downloader = stac_async::Downloader::new(item);
    /// ```
    pub fn new(mut stac: T) -> Result<Downloader<T>> {
        let file_name = if let Some(href) = stac.href().map(|href| href.to_string()) {
            stac.make_relative_links_absolute(&href)?;
            // TODO detect if this should be geojson or json
            stac.links_mut().push(Link::new(&href, "canonical"));
            href.rsplit_once('/')
                .map(|(_, file_name)| file_name.to_string())
        } else {
            let _ = stac.remove_relative_links();
            None
        };
        Ok(Downloader {
            stac,
            client: Client::new(),
            file_name: file_name.unwrap_or_else(|| DEFAULT_FILE_NAME.to_string()),
            create_directory: DEFAULT_CREATE_DIRECTORY,
            sender: None,
            write_stac: DEFAULT_WRITE_STAC,
        })
    }

    /// Should the downloader create the output directory?
    ///
    /// Defaults to `true`.
    ///
    /// # Examples
    ///
    /// ```
    /// let item: stac::Item = stac::read("data/simple-item.json").unwrap();
    /// let downloader = stac_async::Downloader::new(item)
    ///     .unwrap()
    ///     .create_directory(false);
    /// ```
    pub fn create_directory(mut self, create_directory: bool) -> Downloader<T> {
        self.create_directory = create_directory;
        self
    }

    /// Set the sender for messages from this downloader.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tokio::sync::mpsc;
    /// use stac_async::Downloader;
    /// use stac::Item;
    ///
    /// let (tx, mut rx)  = mpsc::channel(100);
    /// let item: Item = stac::read("data/simple-item.json").unwrap();
    /// let downloader = Downloader::new(item)
    ///     .unwrap()
    ///     .with_sender(tx);
    ///
    /// # tokio_test::block_on(async {
    /// tokio::spawn(async move {
    ///     downloader.download(".").await.unwrap()
    /// });
    ///
    /// while let Some(message) = rx.recv().await {
    ///     dbg!(message);
    /// }
    /// # })
    /// ```
    pub fn with_sender(mut self, sender: Sender<Message>) -> Downloader<T> {
        self.sender = Some(sender);
        self
    }

    /// Downloads assets to the specified directory.
    ///
    /// Consumes this downloader, and returns the modified object.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let item: stac::Item = stac::read("data/simple-item.json").unwrap();
    /// let downloader = stac_async::Downloader::new(item).unwrap();
    /// # tokio_test::block_on(async {
    /// let item = downloader.download("outdir").await.unwrap();
    /// # })
    /// ```
    pub async fn download(mut self, directory: impl AsRef<Path>) -> Result<T> {
        let mut join_set = JoinSet::new();
        let directory = directory.as_ref();
        if self.create_directory {
            self.send(|| Message::CreateDirectory(directory.to_path_buf()))
                .await?;
            tokio::fs::create_dir_all(directory).await?;
        }
        for asset_downloader in self.asset_downloaders() {
            let directory = directory.to_path_buf();
            let _ = join_set.spawn(async move { asset_downloader.download(directory) });
        }
        let path = directory.join(&self.file_name);
        self.stac.set_link(Link::self_(path.to_string_lossy()));
        while let Some(result) = join_set.join_next().await {
            // TODO we should allow some assets to gracefully fail, maybe?
            let (key, asset) = result?.await?;
            let _ = self.stac.assets_mut().insert(key, asset);
        }
        self.send(|| Message::FinishedAllDownloads).await?;
        if self.write_stac {
            self.send(|| Message::WriteStac(path.clone())).await?;
            crate::write_json_to_path(path, serde_json::to_value(self.stac.clone())?).await?;
        }
        Ok(self.stac)
    }

    fn asset_downloaders(&mut self) -> Vec<AssetDownloader> {
        self.stac
            .assets_mut()
            .drain()
            .enumerate()
            .map(|(id, (key, asset))| AssetDownloader {
                id,
                key,
                asset,
                client: self.client.clone(),
                sender: self.sender.clone(),
            })
            .collect()
    }

    async fn send(&mut self, f: impl Fn() -> Message) -> Result<()> {
        if let Some(sender) = &mut self.sender {
            sender.send(f()).await.map_err(Error::from)
        } else {
            Ok(())
        }
    }
}

impl AssetDownloader {
    async fn download(mut self, directory: impl AsRef<Path>) -> Result<(String, Asset)> {
        let id = self.id;
        let url = Url::parse(&self.asset.href)?;
        let file_name = url
            .path_segments()
            .and_then(|s| s.last().map(|s| s.to_string()))
            .unwrap_or_else(|| self.key.clone());
        self.send(|| Message::GetAsset {
            id,
            url: url.clone(),
        })
        .await?;
        let mut response = self
            .client
            .get(&self.asset.href)
            .send()
            .await
            .and_then(|response| response.error_for_status())?;
        let content_length = response.content_length();
        self.send(|| Message::GotAsset { id, content_length })
            .await?;
        let path = directory.as_ref().join(file_name.clone());
        let mut file = File::create(path).await?;
        let mut bytes_written = 0;
        while let Some(chunk) = response.chunk().await? {
            file.write_all(&chunk).await?;
            bytes_written += chunk.len();
            self.try_send(|| Message::Update { id, bytes_written });
        }
        self.try_send(|| Message::FinishedDownload(id));
        self.asset.href = format!("./{}", file_name);
        Ok((self.key, self.asset))
    }

    async fn send(&mut self, f: impl Fn() -> Message) -> Result<()> {
        if let Some(sender) = &mut self.sender {
            sender.send(f()).await.map_err(Error::from)
        } else {
            Ok(())
        }
    }

    /// Sometimes we want to send without erroring, e.g. during a download when
    /// the buffer might fill up.
    fn try_send(&mut self, f: impl Fn() -> Message) {
        if let Some(sender) = &mut self.sender {
            let _ = sender.try_send(f());
        }
    }
}

impl Download for Item {}
impl Download for Collection {}

#[cfg(test)]
mod tests {
    use super::Download;
    use mockito::Server;
    use stac::{Asset, Href, Item, Link, Links};
    use tempdir::TempDir;

    #[tokio::test]
    async fn download() {
        let mut server = Server::new_async().await;
        let download = server
            .mock("GET", "/asset.tif")
            .with_body("fake geotiff, sorry!")
            .create_async()
            .await;
        let mut item = Item::new("an-id");
        item.set_link(Link::collection("./collection.json"));
        let _ = item.assets.insert(
            "data".to_string(),
            Asset::new(format!("{}/asset.tif", server.url())),
        );
        item.set_href("http://stac-async-rs.test/item.json");
        let temp_dir = TempDir::new("download").unwrap();
        let item = item.download(temp_dir.path()).await.unwrap();
        download.assert_async().await;
        assert_eq!(
            item.link("canonical").unwrap().href,
            "http://stac-async-rs.test/item.json"
        );
        assert_eq!(
            item.collection_link().unwrap().href,
            "http://stac-async-rs.test/collection.json"
        );
        let path = temp_dir.path().join("item.json");
        assert_eq!(item.self_link().unwrap().href, path.to_string_lossy());
        for asset in item.assets.values() {
            assert!(temp_dir.path().join(&asset.href).exists());
        }
        let _: Item = crate::read(path.to_string_lossy()).await.unwrap();
    }
}