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
use super::CompletedState;
use digest::Digest;
use failure::Fail;
use filetime::{self, FileTime};
use futures::{self, future::ok as OkFuture, Future};
use hashing::hash_from_path;
use std::{
    fs::{remove_file as remove_file_sync, File as SyncFile},
    io::{self, Write},
    path::Path,
    sync::Arc,
};
use tokio::fs::{remove_file, rename};
use {FetchError, FetchErrorKind, FetchEvent};

/// This state manages renaming to the destination, and setting the timestamp of the fetched file.
pub struct FetchedState {
    pub future: Box<dyn Future<Item = Option<Option<FileTime>>, Error = FetchError> + Send>,
    pub download_location: Arc<Path>,
    pub final_destination: Arc<Path>,
    pub(crate) progress: Option<Arc<dyn Fn(FetchEvent) + Send + Sync>>
}

impl FetchedState {
    /// Apply a `Digest`-able hash method to the downloaded file, and compare the checksum to the
    /// given input.
    pub fn with_checksum<H: Digest>(self, checksum: Arc<str>) -> Self {
        let download_location = self.download_location;
        let final_destination = self.final_destination;
        let cb = self.progress.clone();

        // Simply "enhance" our future to append an extra action.
        let new_future = {
            let download_location = download_location.clone();
            self.future.and_then(|resp| {
                futures::future::lazy(move || {
                    if resp.is_none() {
                        return Ok(resp);
                    }

                    if let Some(cb) = cb {
                        cb(FetchEvent::Processing);
                    }

                    hash_from_path::<H>(&download_location, &checksum).map_err(|why| {
                        why.context(FetchErrorKind::DestinationHash(
                            download_location.to_path_buf(),
                        ))
                    })?;

                    Ok(resp)
                })
            })
        };

        Self {
            future: Box::new(new_future),
            download_location: download_location,
            final_destination: final_destination,
            progress: self.progress
        }
    }

    /// Replaces and renames the fetched file, then sets the file times.
    pub fn then_rename(self) -> CompletedState<impl Future<Item = (), Error = FetchError> + Send> {
        let partial = self.download_location;
        let dest = self.final_destination;
        let dest_copy = dest.clone();

        let future =
            {
                let dest = dest.clone();
                self.future
                    .and_then(move |ftime| {
                        let requires_rename = ftime.is_some();

                        // Remove the original file and rename, if required.
                        let rename_future: Box<
                            dyn Future<Item = (), Error = FetchError> + Send,
                        > = {
                            if requires_rename && partial != dest {
                                if dest.exists() {
                                    let d1 = dest.clone();
                                    let future =
                                        remove_file(dest.clone())
                                            .map_err(move |why| {
                                                FetchError::from(why.context(
                                                    FetchErrorKind::Remove(d1.to_path_buf()),
                                                ))
                                            })
                                            .and_then(move |_| {
                                                rename(partial.clone(), dest.clone())
                                                    .map_err(move |why| {
                                                        why.context(FetchErrorKind::Rename {
                                                            src: partial.to_path_buf(),
                                                            dst: dest.to_path_buf(),
                                                        })
                                                    })
                                                    .map_err(FetchError::from)
                                            });

                                    Box::new(future)
                                } else {
                                    let future = rename(partial.clone(), dest.clone())
                                        .map_err(move |why| {
                                            why.context(FetchErrorKind::Rename {
                                                src: partial.to_path_buf(),
                                                dst: dest.to_path_buf(),
                                            })
                                        })
                                        .map_err(FetchError::from);

                                    Box::new(future)
                                }
                            } else {
                                Box::new(OkFuture(()))
                            }
                        };

                        rename_future.map(move |_| ftime)
                    })
                    .and_then(|ftime| {
                        futures::future::lazy(move || {
                            if let Some(Some(ftime)) = ftime {
                                debug!(
                                    "setting timestamp on {} to {:?}",
                                    dest_copy.as_ref().display(),
                                    ftime
                                );

                                filetime::set_file_times(dest_copy.as_ref(), ftime, ftime)
                                    .map_err(|why| {
                                        FetchError::from(why.context(FetchErrorKind::FileTime(
                                            dest_copy.to_path_buf(),
                                        )))
                                    })?;
                            }

                            Ok(())
                        })
                    })
            };

        CompletedState {
            future: Box::new(future),
            destination: dest,
        }
    }

    /// Processes the fetched file, storing the output to the destination, then setting the file times.
    ///
    /// Use this to decompress an archive if the fetched file was an archive.
    pub fn then_process<F>(
        self,
        construct_writer: F,
    ) -> CompletedState<impl Future<Item = (), Error = FetchError> + Send>
    where
        F: Fn(SyncFile) -> io::Result<Box<dyn Write + Send>> + Send,
    {
        let partial = self.download_location;
        let dest = self.final_destination;
        let dest_copy = dest.clone();

        let future =
            {
                let dest = dest.clone();
                self.future
                    .and_then(move |ftime| {
                        let requires_processing = ftime.is_some();

                        let decompress_future = {
                            futures::future::lazy(move || {
                                if requires_processing {
                                    debug!("constructing decompressor for {}", dest.display());
                                    let file = SyncFile::create(dest.as_ref()).map_err(|why| {
                                        FetchError::from(why.context(
                                            FetchErrorKind::CreateDestination(dest.to_path_buf()),
                                        ))
                                    })?;

                                    let mut destination = construct_writer(file).map_err(|why| {
                                        FetchError::from(why.context(
                                            FetchErrorKind::WriterConstruction(dest.to_path_buf()),
                                        ))
                                    })?;

                                    let mut partial_file = SyncFile::open(partial.as_ref())
                                        .map_err(|why| {
                                            FetchError::from(why.context(FetchErrorKind::Open(
                                                partial.to_path_buf(),
                                            )))
                                        })?;

                                    debug!("processing to {}", dest.display());
                                    io::copy(&mut partial_file, &mut destination).map_err(|why| {
                                        FetchError::from(why.context(FetchErrorKind::Copy {
                                            src: partial.to_path_buf(),
                                            dst: dest.to_path_buf(),
                                        }))
                                    })?;

                                    debug!("removing partial file at {}", partial.display());
                                    remove_file_sync(partial.as_ref()).map_err(|why| {
                                        FetchError::from(
                                            why.context(FetchErrorKind::Remove(
                                                partial.to_path_buf(),
                                            )),
                                        )
                                    })?;
                                }

                                Ok(())
                            })
                        };

                        decompress_future.map(move |_| ftime)
                    })
                    .and_then(|ftime| {
                        futures::future::lazy(move || {
                            if let Some(Some(ftime)) = ftime {
                                debug!(
                                    "setting timestamp on {} to {:?}",
                                    dest_copy.display(),
                                    ftime
                                );

                                filetime::set_file_times(dest_copy.as_ref(), ftime, ftime)
                                    .map_err(|why| {
                                        FetchError::from(why.context(FetchErrorKind::FileTime(
                                            dest_copy.to_path_buf(),
                                        )))
                                    })?;
                            }

                            Ok(())
                        })
                    })
            };

        CompletedState {
            future: Box::new(future),
            destination: dest,
        }
    }

    pub fn into_future(
        self,
    ) -> impl Future<Item = Option<Option<FileTime>>, Error = FetchError> + Send {
        self.future
    }
}