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
//! Downloading mod files.
use std::error::Error as StdError;
use std::fmt;
use std::path::Path;

use bytes::Bytes;
use futures_core::Stream;
use futures_util::{SinkExt, StreamExt, TryFutureExt, TryStreamExt};
use reqwest::{Method, Response, StatusCode};
use tokio::fs::File as AsyncFile;
use tokio::io::BufWriter;
use tokio_util::codec::{BytesCodec, FramedWrite};
use tracing::debug;

use crate::error::{self, Kind, Result};
use crate::types::mods::{File, Mod};
use crate::Modio;

/// A `Downloader` can be used to stream a mod file or save the file to a local file.
/// Constructed with [`Modio::download`].
pub struct Downloader {
    modio: Modio,
    action: DownloadAction,
}

impl Downloader {
    pub(crate) fn new(modio: Modio, action: DownloadAction) -> Self {
        Self { modio, action }
    }

    /// Save the mod file to a local file.
    ///
    /// # Example
    /// ```no_run
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let modio = modio::Modio::new("api-key")?;
    /// let action = modio::DownloadAction::Primary {
    ///     game_id: 5,
    ///     mod_id: 19,
    /// };
    ///
    /// modio.download(action).save_to_file("mod.zip").await?;
    /// #     Ok(())
    /// # }
    /// ```
    pub async fn save_to_file<P: AsRef<Path>>(self, file: P) -> Result<()> {
        let out = AsyncFile::create(file).map_err(error::decode).await?;
        let out = BufWriter::with_capacity(512 * 512, out);
        let out = FramedWrite::new(out, BytesCodec::new());
        let out = out.sink_map_err(error::decode);
        self.stream().forward(out).await
    }

    /// Get the full mod file as `Bytes`.
    ///
    /// # Example
    /// ```no_run
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let modio = modio::Modio::new("api-key")?;
    /// let action = modio::DownloadAction::Primary {
    ///     game_id: 5,
    ///     mod_id: 19,
    /// };
    ///
    /// let bytes = modio.download(action).bytes().await?;
    /// #     Ok(())
    /// # }
    /// ```
    pub async fn bytes(self) -> Result<Bytes> {
        let resp = request_file(self.modio, self.action).await?;
        resp.bytes().map_err(error::request).await
    }

    /// `Stream` of bytes of the mod file.
    ///
    /// # Example
    /// ```no_run
    /// use futures_util::TryStreamExt;
    ///
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let modio = modio::Modio::new("api-key")?;
    /// let action = modio::DownloadAction::Primary {
    ///     game_id: 5,
    ///     mod_id: 19,
    /// };
    ///
    /// let mut st = Box::pin(modio.download(action).stream());
    /// while let Some(bytes) = st.try_next().await? {
    ///     println!("Bytes: {:?}", bytes);
    /// }
    /// #     Ok(())
    /// # }
    /// ```
    pub fn stream(self) -> impl Stream<Item = Result<Bytes>> {
        request_file(self.modio, self.action)
            .and_then(|res| async { Ok(res.bytes_stream().map_err(error::request)) })
            .try_flatten_stream()
    }
}

async fn request_file(modio: Modio, action: DownloadAction) -> Result<Response> {
    let url = match action {
        DownloadAction::Primary { game_id, mod_id } => {
            let modref = modio.mod_(game_id, mod_id);
            let m = modref
                .get()
                .map_err(|e| match e.kind() {
                    Kind::Status(StatusCode::NOT_FOUND) => {
                        error::download_mod_not_found(game_id, mod_id)
                    }
                    _ => e,
                })
                .await?;
            if let Some(file) = m.modfile {
                file.download.binary_url
            } else {
                return Err(error::download_no_primary(game_id, mod_id));
            }
        }
        DownloadAction::FileObj(file) => file.download.binary_url,
        DownloadAction::File {
            game_id,
            mod_id,
            file_id,
        } => {
            let fileref = modio.mod_(game_id, mod_id).file(file_id);
            let file = fileref
                .get()
                .map_err(|e| match e.kind() {
                    Kind::Status(StatusCode::NOT_FOUND) => {
                        error::download_file_not_found(game_id, mod_id, file_id)
                    }
                    _ => e,
                })
                .await?;
            file.download.binary_url
        }
        DownloadAction::Version {
            game_id,
            mod_id,
            version,
            policy,
        } => {
            use crate::files::filters::{DateAdded, Version};
            use crate::filter::prelude::*;
            use ResolvePolicy::*;

            let filter = Version::eq(version.clone())
                .order_by(DateAdded::desc())
                .limit(2);

            let files = modio.mod_(game_id, mod_id).files();
            let mut list = files
                .search(filter)
                .first_page()
                .map_err(|e| match e.kind() {
                    Kind::Status(StatusCode::NOT_FOUND) => {
                        error::download_mod_not_found(game_id, mod_id)
                    }
                    _ => e,
                })
                .await?;

            let (file, error) = match (list.len(), policy) {
                (0, _) => (
                    None,
                    Some(error::download_version_not_found(game_id, mod_id, version)),
                ),
                (1, _) => (Some(list.remove(0)), None),
                (_, Latest) => (Some(list.remove(0)), None),
                (_, Fail) => (
                    None,
                    Some(error::download_multiple_files(game_id, mod_id, version)),
                ),
            };

            if let Some(file) = file {
                file.download.binary_url
            } else {
                return Err(error.expect("bug in previous match!"));
            }
        }
    };

    debug!("downloading file: {}", url);
    modio
        .client
        .request(Method::GET, url)
        .send()
        .map_err(error::builder_or_request)
        .await?
        .error_for_status()
        .map_err(error::request)
}

/// Defines the action that is performed for [`Modio::download`].
#[derive(Debug)]
pub enum DownloadAction {
    /// Download the primary modfile of a mod.
    Primary { game_id: u32, mod_id: u32 },
    /// Download a specific modfile of a mod.
    File {
        game_id: u32,
        mod_id: u32,
        file_id: u32,
    },
    /// Download a specific modfile.
    FileObj(Box<File>),
    /// Download a specific version of a mod.
    Version {
        game_id: u32,
        mod_id: u32,
        version: String,
        policy: ResolvePolicy,
    },
}

/// Defines the policy for `DownloadAction::Version` when multiple files are found.
#[derive(Debug)]
pub enum ResolvePolicy {
    /// Download the latest file.
    Latest,
    /// Return with [`Error::MultipleFilesFound`] as source error.
    Fail,
}

/// The Errors that may occur when using [`Modio::download`].
#[derive(Debug)]
pub enum Error {
    /// The mod has not found.
    ModNotFound { game_id: u32, mod_id: u32 },
    /// The mod has no primary file.
    NoPrimaryFile { game_id: u32, mod_id: u32 },
    /// The specific file of a mod was not found.
    FileNotFound {
        game_id: u32,
        mod_id: u32,
        file_id: u32,
    },
    /// Multiple files for a given version were found and the policy was set to
    /// [`ResolvePolicy::Fail`].
    MultipleFilesFound {
        game_id: u32,
        mod_id: u32,
        version: String,
    },
    /// No file for a given version was found.
    VersionNotFound {
        game_id: u32,
        mod_id: u32,
        version: String,
    },
}

impl StdError for Error {}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::ModNotFound { game_id, mod_id } => write!(
                fmt,
                "Mod {{id: {1}, game_id: {0}}} not found.",
                game_id, mod_id,
            ),
            Error::FileNotFound {
                game_id,
                mod_id,
                file_id,
            } => write!(
                fmt,
                "Mod {{id: {1}, game_id: {0}}}: File {{ id: {2} }} not found.",
                game_id, mod_id, file_id,
            ),
            Error::MultipleFilesFound {
                game_id,
                mod_id,
                version,
            } => write!(
                fmt,
                "Mod {{id: {1}, game_id: {0}}}: Multiple files found for version '{2}'.",
                game_id, mod_id, version,
            ),
            Error::NoPrimaryFile { game_id, mod_id } => write!(
                fmt,
                "Mod {{id: {1}, game_id: {0}}} Mod has no primary file.",
                game_id, mod_id,
            ),
            Error::VersionNotFound {
                game_id,
                mod_id,
                version,
            } => write!(
                fmt,
                "Mod {{id: {1}, game_id: {0}}}: No file with version '{2}' found.",
                game_id, mod_id, version,
            ),
        }
    }
}

/// Convert `Mod` to [`DownloadAction::File`] or [`DownloadAction::Primary`] if `Mod::modfile` is `None`
impl From<Mod> for DownloadAction {
    fn from(m: Mod) -> DownloadAction {
        if let Some(file) = m.modfile {
            DownloadAction::from(file)
        } else {
            DownloadAction::Primary {
                game_id: m.game_id,
                mod_id: m.id,
            }
        }
    }
}

/// Convert `File` to [`DownloadAction::FileObj`]
impl From<File> for DownloadAction {
    fn from(file: File) -> DownloadAction {
        DownloadAction::FileObj(Box::new(file))
    }
}

/// Convert `(u32, u32)` to [`DownloadAction::Primary`]
impl From<(u32, u32)> for DownloadAction {
    fn from((game_id, mod_id): (u32, u32)) -> DownloadAction {
        DownloadAction::Primary { game_id, mod_id }
    }
}

/// Convert `(u32, u32, u32)` to [`DownloadAction::File`]
impl From<(u32, u32, u32)> for DownloadAction {
    fn from((game_id, mod_id, file_id): (u32, u32, u32)) -> DownloadAction {
        DownloadAction::File {
            game_id,
            mod_id,
            file_id,
        }
    }
}

/// Convert `(u32, u32, String)` to [`DownloadAction::Version`] with resolve policy
/// set to `ResolvePolicy::Latest`
impl From<(u32, u32, String)> for DownloadAction {
    fn from((game_id, mod_id, version): (u32, u32, String)) -> DownloadAction {
        DownloadAction::Version {
            game_id,
            mod_id,
            version,
            policy: ResolvePolicy::Latest,
        }
    }
}

/// Convert `(u32, u32, &'a str)` to [`DownloadAction::Version`] with resolve policy
/// set to `ResolvePolicy::Latest`
impl<'a> From<(u32, u32, &'a str)> for DownloadAction {
    fn from((game_id, mod_id, version): (u32, u32, &'a str)) -> DownloadAction {
        DownloadAction::Version {
            game_id,
            mod_id,
            version: version.to_string(),
            policy: ResolvePolicy::Latest,
        }
    }
}