piston-mc 0.1.2-beta

A library for interacting with mojangs piston-mc api
Documentation
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
#![doc = include_str!("../.wiki/VersionManifest.md")]

#[cfg(feature = "assets")]
use crate::assets::Assets;
use crate::manifest_v2::ReleaseType;
#[cfg(any(feature = "downloads", feature = "assets"))]
use anyhow::Result;
#[cfg(feature = "downloads")]
use anyhow::anyhow;
use anyhow::bail;
use reqwest::Client;
use serde::{Deserialize, Serialize};
#[cfg(feature = "downloads")]
use simple_download_utility::{DownloadProgress, download_and_validate_file, download_file};
use simple_download_utility::{FileDownloadArguments, MultiDownloadProgress, download_multiple_files, download_multiple_files_with_client};
use std::collections::HashMap;
#[cfg(feature = "downloads")]
use std::path::Path;
use tokio::sync::mpsc::Sender;

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct VersionManifest {
    pub id: String,
    #[serde(rename = "mainClass")]
    pub main_class: String,
    #[serde(rename = "minimumLauncherVersion")]
    pub minimal_launcher_version: u8,
    #[serde(rename = "releaseTime")]
    pub release_time: chrono::DateTime<chrono::Utc>,
    pub time: chrono::DateTime<chrono::Utc>,
    #[serde(rename = "type")]
    pub release_type: ReleaseType,
    #[serde(alias = "minecraftArguments")]
    pub arguments: Arguments,
    #[serde(rename = "assetIndex")]
    pub asset_index: AssetIndex,
    pub assets: String,
    #[serde(rename = "complianceLevel", skip_serializing_if = "Option::is_none")]
    pub compliance_level: Option<u8>,
    pub downloads: Downloads,
    #[serde(rename = "javaVersion")]
    pub java_version: Option<JavaVersion>,
    pub libraries: Vec<LibraryItem>,
}

//#[derive(Serialize, Deserialize, Clone, Debug)]
//pub struct Libraries{
//    pub records: Vec<LibraryItem>
//}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(untagged)]
pub enum Arguments {
    Post113(Post113),
    Pre113(String),
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Post113 {
    pub game: Vec<GameArgument>,
    pub jvm: Vec<GameArgument>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(untagged)]
pub enum GameArgument {
    /// Simple string argument like "--username"
    Plain(String),
    /// Conditional argument with rules
    Conditional(ConditionalArgument),
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ConditionalArgument {
    pub rules: Vec<Rule>,
    pub value: ArgumentValue,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(untagged)]
pub enum ArgumentValue {
    /// Single value like "--demo"
    Single(String),
    /// Multiple values like ["--width", "${resolution_width}"]
    Multiple(Vec<String>),
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Rule {
    pub action: String,
    #[serde(default)]
    pub features: Option<HashMap<String, bool>>,
    #[serde(default)]
    pub os: Option<OsRule>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct OsRule {
    pub name: Option<String>,
    pub arch: Option<String>,
    /// Regex pattern for OS version matching (used in older versions)
    pub version: Option<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct AssetIndex {
    pub id: String,
    pub sha1: String,
    pub size: u64,
    #[serde(rename = "totalSize")]
    pub total_size: u64,
    pub url: String,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Downloads {
    pub client: Download,
    pub server: Option<Download>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Download {
    #[serde(skip_serializing_if = "Option::is_none", alias = "path")]
    pub id: Option<String>,
    pub sha1: String,
    pub size: u64,
    pub url: String,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct JavaVersion {
    pub component: String,
    #[serde(rename = "majorVersion")]
    pub major_version: u8,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Logging {
    pub client: ClientLogging,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ClientLogging {
    pub argument: String,
    #[serde(rename = "type")]
    pub log_type: String,
    pub file: Download,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct LibraryItem {
    pub name: String,
    pub downloads: LibraryDownload,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rules: Option<Vec<Rule>>,
    /// Native library mappings (OS name -> classifier key)
    /// Used for platform-specific native libraries
    #[serde(skip_serializing_if = "Option::is_none")]
    pub natives: Option<HashMap<String, String>>,
    /// Extraction rules for native libraries
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extract: Option<ExtractRules>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ExtractRules {
    /// Paths to exclude when extracting (e.g., ["META-INF/"])
    pub exclude: Vec<String>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct LibraryDownload {
    /// Main artifact download (may be absent for native-only libraries)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub artifact: Option<Download>,
    /// Platform-specific native classifiers
    #[serde(skip_serializing_if = "Option::is_none")]
    pub classifiers: Option<HashMap<String, Download>>,
}

#[cfg(feature = "downloads")]
impl VersionManifest {
    pub async fn from_url(url: impl AsRef<str>) -> Result<Self> {
        let url = url.as_ref();
        let response = reqwest::get(url).await?;
        let text = response.text().await?;
        let json_result = serde_json::from_str::<Self>(&text);

        #[cfg(feature = "log")]
        if let Err(ref e) = json_result {
            let line = e.line();
            let column = e.column();
            error!("Failed to deserialize VersionManifest from {}: {}", url, e);
            error!("Error at line {}, column {}", line, column);

            // Show context around the error (60 chars before and after)
            let error_offset = text.lines().take(line - 1).map(|l| l.len() + 1).sum::<usize>() + column - 1;
            let start = error_offset.saturating_sub(60);
            let end = (error_offset + 60).min(text.len());
            let context = &text[start..end];

            error!("Context around error: {}", context);
        }

        Ok(json_result?)
    }

    pub async fn download_client(
        &self,
        path: impl AsRef<Path>,
        validate: bool,
        sender: Option<tokio::sync::mpsc::Sender<DownloadProgress>>,
    ) -> Result<()> {
        let path = path.as_ref();
        let url = &self.downloads.client.url;
        let hash = &self.downloads.client.sha1;

        if validate {
            download_and_validate_file(url, path, hash, sender).await?;
        } else {
            download_file(url, path, sender).await?;
        }

        Ok(())
    }

    pub async fn download_server(
        &self,
        path: impl AsRef<Path>,
        validate: bool,
        sender: Option<tokio::sync::mpsc::Sender<DownloadProgress>>,
    ) -> Result<()> {
        let path = path.as_ref();
        if let Some(server) = &self.downloads.server {
            let url = &server.url;
            let hash = &server.sha1;

            if validate {
                download_and_validate_file(url, path, hash, sender).await?;
            } else {
                download_file(url, path, sender).await?;
            }
        } else {
            return Err(anyhow!("No server download available"));
        }

        Ok(())
    }
}

pub trait LibraryItemDownloader {
    fn download(&self, directory: impl AsRef<Path>, parallel: u16, sender: Option<Sender<MultiDownloadProgress>>)
    -> impl Future<Output = Result<()>>;
    fn download_with_client(
        &self,
        client: &Client,
        directory: impl AsRef<Path>,
        parallel: u16,
        sender: Option<Sender<MultiDownloadProgress>>,
    ) -> impl Future<Output = Result<()>>;
}

#[cfg(feature = "downloads")]
impl LibraryItemDownloader for Vec<LibraryItem> {
    async fn download(&self, directory: impl AsRef<Path>, parallel: u16, sender: Option<Sender<MultiDownloadProgress>>) -> Result<()> {
        let client = Client::new();
        self.download_with_client(&client, directory, parallel, sender).await
    }

    async fn download_with_client(
        &self,
        client: &Client,
        directory: impl AsRef<Path>,
        parallel: u16,
        sender: Option<Sender<MultiDownloadProgress>>,
    ) -> Result<()> {
        let directory = directory.as_ref();
        if !directory.exists() {
            tokio::fs::create_dir_all(&directory).await?;
        }

        let download_items: Vec<FileDownloadArguments> = self
            .iter()
            .filter_map(|item| {
                let classifiers = item.downloads.classifiers.clone();
                let artifact = item.downloads.artifact.clone();

                let url: String = if let Some(classifiers) = &classifiers {
                    #[cfg(target_os = "windows")]
                    let name = "natives-windows";
                    #[cfg(target_os = "linux")]
                    let name = "natives-linux";
                    #[cfg(target_os = "macos")]
                    let name = "natives-osx";

                    if let Some(native) = classifiers.get(name) {
                        native.url.clone()
                    } else {
                        return None;
                    }
                } else if let Some(artifact) = &artifact {
                    artifact.url.clone()
                } else {
                    return None;
                };

                let sha: String = if let Some(classifiers) = &classifiers {
                    #[cfg(target_os = "windows")]
                    let name = "natives-windows";
                    #[cfg(target_os = "linux")]
                    let name = "natives-linux";
                    #[cfg(target_os = "macos")]
                    let name = "natives-osx";

                    if let Some(native) = classifiers.get(name) {
                        native.sha1.clone()
                    } else {
                        return None;
                    }
                } else if let Some(artifact) = &artifact {
                    artifact.sha1.clone()
                } else {
                    return None;
                };

                let path: String = if let Some(classifiers) = classifiers {
                    #[cfg(target_os = "windows")]
                    let name = "natives-windows";
                    #[cfg(target_os = "linux")]
                    let name = "natives-linux";
                    #[cfg(target_os = "macos")]
                    let name = "natives-osx";

                    if let Some(native) = classifiers.get(name)
                        && let Some(path) = &native.id
                    {
                        path.clone()
                    } else {
                        return None;
                    }
                } else if let Some(artifact) = artifact
                    && let Some(path) = artifact.id
                {
                    path.clone()
                } else {
                    return None;
                };

                Some(FileDownloadArguments { url, sha1: Some(sha), sender: None, path: directory.join(path).to_string_lossy().to_string() })
            })
            .collect();

        if let Err(e) = download_multiple_files_with_client(client, download_items, parallel, sender).await {
            bail!("Download failed: {}", e);
        }

        Ok(())
    }
}

#[cfg(feature = "assets")]
impl VersionManifest {
    pub async fn assets(&self) -> Result<Assets> {
        Assets::from_url(&self.asset_index.url).await
    }
}

#[cfg(test)]
#[cfg(feature = "downloads")]
mod test {
    use crate::manifest_v2::ManifestV2;
    #[cfg(feature = "log")]
    use crate::setup_logging;
    use futures_util::{StreamExt, stream};

    #[tokio::test]
    async fn download_libraries() {
        use crate::version_manifest::LibraryItemDownloader;
        #[cfg(feature = "log")]
        setup_logging();
        let manifest = ManifestV2::fetch().await.unwrap();
        let client = reqwest::Client::new();
        let client = std::sync::Arc::new(client);
        let results: Vec<anyhow::Result<()>> = stream::iter(manifest.versions)
            .map(|version| {
                let client = std::sync::Arc::clone(&client);
                async move {
                    let manifest = version.manifest().await?;
                    info!("Downloading libraries for minecraft {}", version.id);
                    manifest
                        .libraries
                        .download_with_client(&client, format!("target/tests/download_libraries/{}", version.id), 150, None)
                        .await
                        .unwrap_or_else(|e| panic!("Failed to download libraries for minecraft version {} - {}", version.id, e));
                    Ok(())
                }
            })
            .buffer_unordered(2)
            .collect()
            .await;

        for result in results {
            assert!(result.is_ok());
        }
    }

    #[tokio::test]
    async fn download_server() {
        use crate::manifest_v2::ManifestV2;
        use crate::version_manifest::VersionManifest;
        #[cfg(feature = "log")]
        setup_logging();

        let manifest = ManifestV2::fetch().await.expect("Failed to fetch assets.");
        let release_id = &manifest.latest.release;
        let version: anyhow::Result<Option<VersionManifest>> = manifest.version(release_id).await;
        if let Ok(Some(version)) = version {
            let output = format!("target/test/server-{}.jar", release_id);
            version.download_server(output, true, None).await.unwrap();
        } else {
            panic!("Failed to fetch version.");
        }
    }

    #[tokio::test]
    async fn download_client() {
        use crate::manifest_v2::ManifestV2;
        use crate::version_manifest::VersionManifest;
        #[cfg(feature = "log")]
        setup_logging();

        let manifest = ManifestV2::fetch().await.expect("Failed to fetch assets.");
        let release_id = &manifest.latest.release;
        let version: anyhow::Result<Option<VersionManifest>> = manifest.version(release_id).await;
        if let Ok(Some(version)) = version {
            let output = format!("target/test/client-{}.jar", release_id);
            version.download_client(output, true, None).await.unwrap();
        } else {
            panic!("Failed to fetch version.");
        }
    }
}