From d4d1d52f456176681da2f532c35fe3c36c2cfa59 Mon Sep 17 00:00:00 2001 From: Lucas Schwiderski Date: Mon, 13 Mar 2023 13:11:28 +0100 Subject: [PATCH] feat(nexusmods): Implement parsing download file names When downloading manually from Nexus, the file name encodes information needed to map the file to the mod object. --- lib/nexusmods/Cargo.toml | 1 + lib/nexusmods/src/lib.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/lib/nexusmods/Cargo.toml b/lib/nexusmods/Cargo.toml index 613aa7e..1c94289 100644 --- a/lib/nexusmods/Cargo.toml +++ b/lib/nexusmods/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" [dependencies] lazy_static = "1.4.0" +regex = "1.7.1" reqwest = { version = "0.11.14" } serde = { version = "1.0.152", features = ["derive"] } serde_json = "1.0.94" diff --git a/lib/nexusmods/src/lib.rs b/lib/nexusmods/src/lib.rs index 3f3fb5e..e761a77 100644 --- a/lib/nexusmods/src/lib.rs +++ b/lib/nexusmods/src/lib.rs @@ -1,6 +1,7 @@ use std::convert::Infallible; use lazy_static::lazy_static; +use regex::Regex; use reqwest::header::{HeaderMap, HeaderValue, InvalidHeaderValue}; use reqwest::{Client, RequestBuilder, Url}; use serde::Deserialize; @@ -87,6 +88,26 @@ impl Api { let req = self.client.get(url); self.send(req).await } + + pub fn parse_file_name>(name: S) -> Option<(String, u64, String, u64)> { + lazy_static! { + static ref RE: Regex = Regex::new(r#"^(?P.+?)-(?P[1-9]\d*)-(?P.+?)-(?P[1-9]\d*)(?:\.\w+)?$"#).unwrap(); + } + + RE.captures(name.as_ref()).and_then(|cap| { + let name = cap.name("name")?; + let mod_id = cap.name("mod_id")?; + let version = cap.name("version")?; + let updated = cap.name("updated")?; + + Some(( + name.as_str().to_string(), + mod_id.as_str().parse().ok()?, + version.as_str().to_string(), + updated.as_str().parse().ok()?, + )) + }) + } } #[cfg(test)] @@ -125,4 +146,15 @@ mod test { .await .expect("failed to query 'mods_id'"); } + + #[test] + fn parse_file_name() { + let file = "Darktide Mod Framework-8-23-3-04-1677966575.zip"; + let (name, mod_id, version, updated) = Api::parse_file_name(file).unwrap(); + + assert_eq!(name, String::from("Darktide Mod Framework")); + assert_eq!(mod_id, 8); + assert_eq!(version, String::from("23-3-04")); + assert_eq!(updated, 1677966575); + } }