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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
//! Downloading mod files.
use std::error::Error as StdError;
use std::fmt;
use std::path::Path;
use bytes::Bytes;
use futures_util::{SinkExt, Stream, 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, Result};
use crate::types::files::File;
use crate::types::id::{FileId, GameId, ModId};
use crate::types::mods::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(Response);
impl Downloader {
pub(crate) async fn new(modio: Modio, action: DownloadAction) -> Result<Self> {
Ok(Self(request_file(modio, action).await?))
}
/// Save the mod file to a local file.
///
/// # Example
/// ```no_run
/// # use modio::types::id::Id;
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let modio = modio::Modio::new("api-key")?;
/// let action = modio::DownloadAction::Primary {
/// game_id: Id::new(5),
/// mod_id: Id::new(19),
/// };
///
/// modio
/// .download(action)
/// .await?
/// .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 = SinkExt::<Bytes>::sink_map_err(out, error::decode);
self.stream().forward(out).await
}
/// Get the full mod file as `Bytes`.
///
/// # Example
/// ```no_run
/// # use modio::types::id::Id;
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let modio = modio::Modio::new("api-key")?;
/// let action = modio::DownloadAction::Primary {
/// game_id: Id::new(5),
/// mod_id: Id::new(19),
/// };
///
/// let bytes = modio.download(action).await?.bytes().await?;
/// # Ok(())
/// # }
/// ```
pub async fn bytes(self) -> Result<Bytes> {
self.0.bytes().map_err(error::request).await
}
/// `Stream` of bytes of the mod file.
///
/// # Example
/// ```no_run
/// use futures_util::TryStreamExt;
///
/// # use modio::types::id::Id;
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let modio = modio::Modio::new("api-key")?;
/// let action = modio::DownloadAction::Primary {
/// game_id: Id::new(5),
/// mod_id: Id::new(19),
/// };
///
/// let mut st = Box::pin(modio.download(action).await?.stream());
/// while let Some(bytes) = st.try_next().await? {
/// println!("Bytes: {:?}", bytes);
/// }
/// # Ok(())
/// # }
/// ```
pub fn stream(self) -> impl Stream<Item = Result<Bytes>> {
self.0.bytes_stream().map_err(error::request)
}
/// Get the content length from the mod file response.
///
/// # Example
/// ```no_run
/// # use modio::types::id::Id;
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let modio = modio::Modio::new("api-key")?;
/// let action = modio::DownloadAction::Primary {
/// game_id: Id::new(5),
/// mod_id: Id::new(19),
/// };
///
/// let content_length = modio
/// .download(action)
/// .await?
/// .content_length()
/// .expect("mod file response should have content length");
/// # Ok(())
/// # }
/// ```
pub fn content_length(&self) -> Option<u64> {
self.0.content_length()
}
}
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.status() {
Some(StatusCode::NOT_FOUND) => {
let source = Error::ModNotFound { game_id, mod_id };
error::download(source)
}
_ => e,
})
.await?;
if let Some(file) = m.modfile {
file.download.binary_url
} else {
let source = Error::NoPrimaryFile { game_id, mod_id };
return Err(error::download(source));
}
}
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.status() {
Some(StatusCode::NOT_FOUND) => {
let source = Error::FileNotFound {
game_id,
mod_id,
file_id,
};
error::download(source)
}
_ => e,
})
.await?;
file.download.binary_url
}
DownloadAction::Version {
game_id,
mod_id,
version,
policy,
} => {
use crate::files::filters::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.status() {
Some(StatusCode::NOT_FOUND) => {
let source = Error::ModNotFound { game_id, mod_id };
error::download(source)
}
_ => e,
})
.await?;
let (file, error) = match (list.len(), policy) {
(0, _) => (
None,
Some(Error::VersionNotFound {
game_id,
mod_id,
version,
}),
),
(1, _) | (_, Latest) => (Some(list.remove(0)), None),
(_, Fail) => (
None,
Some(Error::MultipleFilesFound {
game_id,
mod_id,
version,
}),
),
};
if let Some(file) = file {
file.download.binary_url
} else {
let source = error.expect("bug in previous match!");
return Err(error::download(source));
}
}
};
debug!("downloading file: {}", url);
modio
.inner
.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: GameId, mod_id: ModId },
/// Download a specific modfile of a mod.
File {
game_id: GameId,
mod_id: ModId,
file_id: FileId,
},
/// Download a specific modfile.
FileObj(Box<File>),
/// Download a specific version of a mod.
Version {
game_id: GameId,
mod_id: ModId,
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: GameId, mod_id: ModId },
/// The mod has no primary file.
NoPrimaryFile { game_id: GameId, mod_id: ModId },
/// The specific file of a mod was not found.
FileNotFound {
game_id: GameId,
mod_id: ModId,
file_id: FileId,
},
/// Multiple files for a given version were found and the policy was set to
/// [`ResolvePolicy::Fail`].
MultipleFilesFound {
game_id: GameId,
mod_id: ModId,
version: String,
},
/// No file for a given version was found.
VersionNotFound {
game_id: GameId,
mod_id: ModId,
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: {mod_id}, game_id: {game_id}}} not found.",
),
Error::FileNotFound {
game_id,
mod_id,
file_id,
} => write!(
fmt,
"Mod {{id: {mod_id}, game_id: {game_id}}}: File {{ id: {file_id} }} not found.",
),
Error::MultipleFilesFound {
game_id,
mod_id,
version,
} => write!(
fmt,
"Mod {{id: {mod_id}, game_id: {game_id}}}: Multiple files found for version '{version}'.",
),
Error::NoPrimaryFile { game_id, mod_id } => write!(
fmt,
"Mod {{id: {mod_id}, game_id: {game_id}}} Mod has no primary file.",
),
Error::VersionNotFound {
game_id,
mod_id,
version,
} => write!(
fmt,
"Mod {{id: {mod_id}, game_id: {game_id}}}: No file with version '{version}' found.",
),
}
}
}
/// 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 `(GameId, ModId)` to [`DownloadAction::Primary`]
impl From<(GameId, ModId)> for DownloadAction {
fn from((game_id, mod_id): (GameId, ModId)) -> DownloadAction {
DownloadAction::Primary { game_id, mod_id }
}
}
/// Convert `(GameId, ModId, FileId)` to [`DownloadAction::File`]
impl From<(GameId, ModId, FileId)> for DownloadAction {
fn from((game_id, mod_id, file_id): (GameId, ModId, FileId)) -> DownloadAction {
DownloadAction::File {
game_id,
mod_id,
file_id,
}
}
}
/// Convert `(GameId, ModId, String)` to [`DownloadAction::Version`] with resolve policy
/// set to `ResolvePolicy::Latest`
impl From<(GameId, ModId, String)> for DownloadAction {
fn from((game_id, mod_id, version): (GameId, ModId, String)) -> DownloadAction {
DownloadAction::Version {
game_id,
mod_id,
version,
policy: ResolvePolicy::Latest,
}
}
}
/// Convert `(GameId, ModId, &'a str)` to [`DownloadAction::Version`] with resolve policy
/// set to `ResolvePolicy::Latest`
impl<'a> From<(GameId, ModId, &'a str)> for DownloadAction {
fn from((game_id, mod_id, version): (GameId, ModId, &'a str)) -> DownloadAction {
DownloadAction::Version {
game_id,
mod_id,
version: version.to_string(),
policy: ResolvePolicy::Latest,
}
}
}