Skip to main content

minecraft_java_rs_core/game/
assets.rs

1use crate::error::LaunchError;
2use crate::launcher::options::LaunchOptions;
3use crate::models::minecraft::{AssetIndexData, AssetItem, MinecraftVersionJson};
4use crate::net::http::fetch_text;
5
6const RESOURCES_BASE: &str = "https://resources.download.minecraft.net";
7
8// ── Public API ────────────────────────────────────────────────────────────────
9
10/// Build the full list of asset items that the launcher must have on disk.
11///
12/// Returns two kinds of [`AssetItem`]:
13/// - `CFile` — the asset-index JSON itself (written verbatim to
14///   `<path>/assets/indexes/<id>.json`).
15/// - `Asset` — each hashed object in the index (downloaded from Mojang CDN).
16///
17/// All paths are **absolute** (prefixed with `options.path`).
18/// If `version_json` has no `asset_index`, an empty `Vec` is returned.
19pub async fn get_assets(
20    options: &LaunchOptions,
21    version_json: &MinecraftVersionJson,
22    client: &reqwest::Client,
23) -> Result<Vec<AssetItem>, LaunchError> {
24    let ai = match &version_json.asset_index {
25        Some(ai) => ai,
26        None => return Ok(vec![]),
27    };
28
29    let raw = fetch_text(client, &ai.url)
30        .await
31        .map_err(LaunchError::InvalidData)?;
32    let data: AssetIndexData = serde_json::from_str(&raw).map_err(|e| {
33        LaunchError::InvalidData(format!("GET {}: failed to parse asset index: {e}", &ai.url))
34    })?;
35
36    let base = &options.path;
37    let mut items: Vec<AssetItem> = Vec::with_capacity(data.objects.len() + 1);
38
39    // The index JSON is stored as a CFile so the downloader writes it verbatim.
40    items.push(AssetItem::CFile {
41        path: base
42            .join("assets")
43            .join("indexes")
44            .join(format!("{}.json", ai.id))
45            .to_string_lossy()
46            .into_owned(),
47        content: raw,
48    });
49
50    for obj in data.objects.values() {
51        let sub = &obj.hash[..2];
52        items.push(AssetItem::Asset {
53            path: base
54                .join("assets")
55                .join("objects")
56                .join(sub)
57                .join(&obj.hash)
58                .to_string_lossy()
59                .into_owned(),
60            sha1: obj.hash.clone(),
61            size: obj.size,
62            url: format!("{RESOURCES_BASE}/{sub}/{}", obj.hash),
63        });
64    }
65
66    Ok(items)
67}
68
69/// Copy legacy assets from the object store into a flat `resources/` tree.
70///
71/// Only meaningful for old Minecraft versions (assets `"legacy"` /
72/// `"pre-1.6"`).  The caller is responsible for deciding when to invoke this
73/// based on [`crate::utils::version_check::is_old`].
74///
75/// If the local index file does not yet exist (assets not downloaded),
76/// this is a no-op.
77pub async fn copy_assets(
78    options: &LaunchOptions,
79    version_json: &MinecraftVersionJson,
80) -> Result<(), LaunchError> {
81    let assets_id = match &version_json.assets {
82        Some(a) => a.clone(),
83        None => return Ok(()),
84    };
85
86    let index_path = options
87        .path
88        .join("assets")
89        .join("indexes")
90        .join(format!("{assets_id}.json"));
91
92    if !index_path.exists() {
93        return Ok(());
94    }
95
96    let raw = tokio::fs::read_to_string(&index_path).await?;
97    let data: AssetIndexData = serde_json::from_str(&raw)?;
98
99    let legacy_dir = match &options.instance {
100        Some(inst) => options.path.join("instances").join(inst).join("resources"),
101        None => options.path.join("resources"),
102    };
103
104    for (file_path, obj) in &data.objects {
105        let sub = &obj.hash[..2];
106        let source = options
107            .path
108            .join("assets")
109            .join("objects")
110            .join(sub)
111            .join(&obj.hash);
112
113        if !source.exists() {
114            continue;
115        }
116
117        let target = legacy_dir.join(file_path);
118
119        if let Some(parent) = target.parent() {
120            tokio::fs::create_dir_all(parent).await?;
121        }
122
123        if !target.exists() {
124            tokio::fs::copy(&source, &target).await?;
125        }
126    }
127
128    Ok(())
129}
130
131// ── Tests ─────────────────────────────────────────────────────────────────────
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use std::path::PathBuf;
137    use tempfile::TempDir;
138
139    fn opts(path: PathBuf) -> LaunchOptions {
140        use crate::launcher::options::{JavaOptions, LoaderConfig, MemoryConfig, ScreenConfig};
141        use crate::models::minecraft::Authenticator;
142        LaunchOptions {
143            path,
144            version: "1.20.4".into(),
145            authenticator: Authenticator {
146                access_token: "tok".into(),
147                name: "Player".into(),
148                uuid: "uuid".into(),
149                xbox_account: None,
150                user_properties: None,
151                client_id: None,
152                client_token: None,
153            },
154            timeout_secs: 10,
155            download_concurrency: 5,
156            verify_concurrency: 4,
157            memory: MemoryConfig::default(),
158            java: JavaOptions::default(),
159            loader: LoaderConfig::default(),
160            screen: ScreenConfig::default(),
161            verify: false,
162            game_args: vec![],
163            jvm_args: vec![],
164            instance: None,
165            url: None,
166            mcp: None,
167            intel_enabled_mac: false,
168            bypass_offline: false,
169            skip_bundle_check: false,
170            force_ipv4: false,
171        }
172    }
173
174    fn version_json_no_assets() -> MinecraftVersionJson {
175        MinecraftVersionJson {
176            id: "1.20.4".into(),
177            version_type: "release".into(),
178            assets: None,
179            asset_index: None,
180            downloads: None,
181            libraries: vec![],
182            arguments: None,
183            minecraft_arguments: None,
184            java_version: None,
185            main_class: None,
186            has_natives: false,
187        }
188    }
189
190    #[tokio::test]
191    async fn get_assets_returns_empty_without_asset_index() {
192        let dir = TempDir::new().unwrap();
193        let client = reqwest::Client::new();
194        let result = get_assets(
195            &opts(dir.path().to_path_buf()),
196            &version_json_no_assets(),
197            &client,
198        )
199        .await
200        .unwrap();
201        assert!(result.is_empty());
202    }
203
204    #[tokio::test]
205    async fn copy_assets_noop_when_no_assets_field() {
206        let dir = TempDir::new().unwrap();
207        let vj = version_json_no_assets();
208        copy_assets(&opts(dir.path().to_path_buf()), &vj)
209            .await
210            .unwrap();
211    }
212
213    #[tokio::test]
214    async fn copy_assets_noop_when_index_missing() {
215        let dir = TempDir::new().unwrap();
216        let mut vj = version_json_no_assets();
217        vj.assets = Some("legacy".into());
218        // index file doesn't exist → should return Ok(()) without creating anything
219        copy_assets(&opts(dir.path().to_path_buf()), &vj)
220            .await
221            .unwrap();
222        assert!(!dir.path().join("resources").exists());
223    }
224
225    #[tokio::test]
226    async fn copy_assets_copies_objects_to_resources() {
227        let dir = TempDir::new().unwrap();
228        let base = dir.path();
229
230        // Write a fake asset object
231        let hash = "aabbccddee112233445566778899001122334455";
232        let sub = &hash[..2];
233        let obj_dir = base.join("assets").join("objects").join(sub);
234        tokio::fs::create_dir_all(&obj_dir).await.unwrap();
235        tokio::fs::write(obj_dir.join(hash), b"fake asset content")
236            .await
237            .unwrap();
238
239        // Write the asset index pointing to it
240        let index_json = format!(
241            r#"{{"objects": {{"sounds/ambient/cave.ogg": {{"hash": "{hash}", "size": 18}}}}}}"#
242        );
243        let idx_dir = base.join("assets").join("indexes");
244        tokio::fs::create_dir_all(&idx_dir).await.unwrap();
245        tokio::fs::write(idx_dir.join("legacy.json"), &index_json)
246            .await
247            .unwrap();
248
249        let mut vj = version_json_no_assets();
250        vj.assets = Some("legacy".into());
251
252        copy_assets(&opts(base.to_path_buf()), &vj).await.unwrap();
253
254        let copied = base
255            .join("resources")
256            .join("sounds")
257            .join("ambient")
258            .join("cave.ogg");
259        assert!(
260            copied.exists(),
261            "asset should have been copied to resources/"
262        );
263        assert_eq!(std::fs::read(&copied).unwrap(), b"fake asset content");
264    }
265
266    #[tokio::test]
267    async fn copy_assets_skips_existing_target() {
268        let dir = TempDir::new().unwrap();
269        let base = dir.path();
270
271        let hash = "aabbccddee112233445566778899001122334455";
272        let sub = &hash[..2];
273        let obj_dir = base.join("assets").join("objects").join(sub);
274        tokio::fs::create_dir_all(&obj_dir).await.unwrap();
275        tokio::fs::write(obj_dir.join(hash), b"new content")
276            .await
277            .unwrap();
278
279        let index_json =
280            format!(r#"{{"objects": {{"file.txt": {{"hash": "{hash}", "size": 11}}}}}}"#);
281        let idx_dir = base.join("assets").join("indexes");
282        tokio::fs::create_dir_all(&idx_dir).await.unwrap();
283        tokio::fs::write(idx_dir.join("legacy.json"), &index_json)
284            .await
285            .unwrap();
286
287        // Pre-create target with different content
288        let resources_dir = base.join("resources");
289        tokio::fs::create_dir_all(&resources_dir).await.unwrap();
290        tokio::fs::write(resources_dir.join("file.txt"), b"original")
291            .await
292            .unwrap();
293
294        let mut vj = version_json_no_assets();
295        vj.assets = Some("legacy".into());
296
297        copy_assets(&opts(base.to_path_buf()), &vj).await.unwrap();
298
299        // Existing file must NOT be overwritten
300        let content = std::fs::read(resources_dir.join("file.txt")).unwrap();
301        assert_eq!(content, b"original");
302    }
303
304    #[tokio::test]
305    async fn copy_assets_uses_instance_resources_dir() {
306        let dir = TempDir::new().unwrap();
307        let base = dir.path();
308
309        let hash = "aabbccddee112233445566778899001122334455";
310        let sub = &hash[..2];
311        let obj_dir = base.join("assets").join("objects").join(sub);
312        tokio::fs::create_dir_all(&obj_dir).await.unwrap();
313        tokio::fs::write(obj_dir.join(hash), b"sound")
314            .await
315            .unwrap();
316
317        let index_json = format!(r#"{{"objects": {{"a.ogg": {{"hash": "{hash}", "size": 5}}}}}}"#);
318        let idx_dir = base.join("assets").join("indexes");
319        tokio::fs::create_dir_all(&idx_dir).await.unwrap();
320        tokio::fs::write(idx_dir.join("legacy.json"), &index_json)
321            .await
322            .unwrap();
323
324        let mut options = opts(base.to_path_buf());
325        options.instance = Some("myworld".into());
326
327        let mut vj = version_json_no_assets();
328        vj.assets = Some("legacy".into());
329
330        copy_assets(&options, &vj).await.unwrap();
331
332        let target = base
333            .join("instances")
334            .join("myworld")
335            .join("resources")
336            .join("a.ogg");
337        assert!(target.exists());
338    }
339}