lyceris 1.1.3

An open source Minecraft launcher library.
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
use core::fmt;
/// This module handles the installation of Minecraft, including downloading
/// necessary files and managing the Java runtime environment.
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use std::{
    env::consts::{ARCH, OS},
    fs,
    path::{Path, PathBuf, MAIN_SEPARATOR_STR},
};
use tokio::{fs::create_dir_all, process::Command};

use crate::{
    error::Error,
    http::{
        downloader::{download, download_multiple},
        fetch::fetch,
    },
    json::{
        java::{JavaFileManifest, JavaManifest},
        version::{
            asset_index::AssetIndex,
            manifest::VersionManifest,
            meta::vanilla::{self, JavaVersion, VersionMeta},
        },
    },
    minecraft::{
        CLASSPATH_SEPARATOR, JAVA_MANIFEST_ENDPOINT, RESOURCES_ENDPOINT, VERSION_MANIFEST_ENDPOINT,
    },
    util::{
        extract::{extract_file, read_file_from_jar},
        hash::calculate_sha1,
        json::{read_json, write_json},
    },
};

use super::{
    config::Config,
    emitter::Emitter,
    loader::Loader,
    parse::{parse_lib_path, ParseRule},
};

/// Represents the type of file being downloaded.
#[derive(Clone)]
pub enum FileType {
    Asset { is_virtual: bool, is_map: bool },
    Library,
    Java,
    Custom,
}

impl fmt::Display for FileType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FileType::Asset { .. } => {
                write!(f, "Asset")
            }
            FileType::Library => write!(f, "Library"),
            FileType::Java => write!(f, "Java"),
            FileType::Custom => write!(f, "Custom"),
        }
    }
}

/// Represents a file to be downloaded, including its metadata.
#[derive(Clone)]
struct DownloadFile {
    file_name: String,
    sha1: String,
    url: String,
    path: PathBuf,
    r#type: FileType,
}

/// Installs the specified version of Minecraft by downloading necessary files
/// and setting up the environment.
///
/// # Parameters
/// - `config`: The configuration for the installation process.
/// - `emitter`: An optional emitter for logging progress.
///
/// # Returns
/// A result indicating success or failure of the installation process.
pub async fn install<T: Loader>(
    config: &Config<T>,
    emitter: Option<&Emitter>,
) -> crate::Result<()> {
    let manifest: VersionManifest =
        fetch(VERSION_MANIFEST_ENDPOINT, config.client.as_ref()).await?;
    let version_json_path = config.get_version_json_path();
    let mut meta: VersionMeta = if !version_json_path.exists() {
        let mut meta =
            fetch_version_meta(&manifest, &config.version, config.client.as_ref()).await?;
        if let Some(loader) = &config.loader {
            meta = loader.merge(&config.into_vanilla(), meta, emitter).await?;
        }
        write_json(&version_json_path, &meta).await?;
        meta
    } else {
        read_json(&version_json_path).await?
    };

    let asset_index_path = config
        .get_indexes_path()
        .join(format!("{}.json", &meta.asset_index.id));
    let asset_index: AssetIndex = if !asset_index_path.exists() {
        let asset_index = fetch(&meta.asset_index.url, config.client.as_ref()).await?;
        write_json(&asset_index_path, &asset_index).await?;
        asset_index
    } else {
        read_json(&asset_index_path).await?
    };

    let natives_path = config.get_natives_path().join(&config.version);
    if !natives_path.is_dir() {
        create_dir_all(&natives_path).await?;
    }

    let check_natives = fs::read_dir(&natives_path)?.count() == 0;
    let mut to_be_extracted = Vec::with_capacity(10);

    let default_java_version = JavaVersion::default();
    let java_version = meta.java_version.as_ref().unwrap_or(&default_java_version);
    let runtime_path = config.get_runtime_path().join(&java_version.component);

    let java_manifest: JavaManifest = fetch(JAVA_MANIFEST_ENDPOINT, config.client.as_ref()).await?;
    let java_url = get_java_url(&java_manifest, java_version)?;
    let java_files: JavaFileManifest = fetch(java_url, config.client.as_ref()).await?;

    let file_map = build_file_map(
        &asset_index,
        &meta,
        &java_files,
        &runtime_path,
        config,
        check_natives,
        &mut to_be_extracted,
    )?;

    download_necessary(
        file_map,
        &config.game_dir,
        asset_index.map_to_resources.unwrap_or_default()
            || asset_index.r#virtual.unwrap_or_default(),
        emitter,
        config.client.as_ref(),
    )
    .await?;

    if !to_be_extracted.is_empty() {
        create_dir_all(&natives_path).await?;
        for extract in to_be_extracted {
            if let Some(path) = extract.path {
                let path = PathBuf::from(path);
                download(&extract.url, &path, emitter, config.client.as_ref()).await?;
                extract_file(&path, &natives_path)?;
            }
        }
    }

    execute_processors_if_exists(&mut meta, config).await?;

    Ok(())
}

/// Fetches the version metadata for the specified version from the manifest.
///
/// # Parameters
/// - `manifest`: The version manifest containing available versions.
/// - `version`: The version to fetch metadata for.
/// - `client`: An optional HTTP client for making requests.
///
/// # Returns
/// The version metadata for the specified version.
async fn fetch_version_meta(
    manifest: &VersionManifest,
    version: &str,
    client: Option<&reqwest::Client>,
) -> crate::Result<VersionMeta> {
    let version_url = manifest
        .versions
        .iter()
        .find(|v| v.id == version)
        .ok_or_else(|| Error::UnknownVersion("Vanilla".to_string()))?
        .url
        .clone();
    fetch(&version_url, client).await
}

/// Gets the download URL for the specified Java version based on the operating system and architecture.
///
/// # Parameters
/// - `java_manifest`: The manifest containing Java version information.
/// - `java_version`: The specific Java version to retrieve the URL for.
///
/// # Returns
/// The download URL for the specified Java version.
fn get_java_url(java_manifest: &JavaManifest, java_version: &JavaVersion) -> crate::Result<String> {
    let os = if OS == "macos" { "mac-os" } else { OS };
    let arch = match ARCH {
        "x86" => {
            if os == "linux" {
                "i386"
            } else {
                "x86"
            }
        }
        "x86_64" => "x64",
        "aarch64" => "arm64",
        _ => return Err(Error::UnsupportedArchitecture),
    };
    let os_arch = if (os == "linux" && arch != "i386")
        || (os == "mac-os" && (arch != "arm64" || java_version.major_version == 8))
    {
        os.to_string()
    } else {
        format!("{}-{}", os, arch)
    };
    java_manifest
        .get(&os_arch)
        .ok_or_else(|| Error::NotFound("Java map by operating system".to_string()))?
        .get(&java_version.component)
        .ok_or_else(|| Error::UnknownVersion("Java version".to_string()))?
        .first()
        .ok_or_else(|| Error::NotFound("Java gamecore".to_string()))
        .map(|entry| &entry.manifest.url)
        .cloned()
}

/// Builds a map of files to be downloaded based on the asset index, version metadata, and Java files.
///
/// # Parameters
/// - `asset_index`: The asset index containing file information.
/// - `meta`: The version metadata.
/// - `java_files`: The Java file manifest.
/// - `runtime_path`: The path to the Java runtime.
/// - `config`: The configuration for the installation process.
/// - `check_natives`: A flag indicating whether to check for native files.
/// - `to_be_extracted`: A mutable vector to store files that need to be extracted.
///
/// # Returns
/// A vector of `DownloadFile` representing the files to be downloaded.
fn build_file_map(
    asset_index: &AssetIndex,
    meta: &VersionMeta,
    java_files: &JavaFileManifest,
    runtime_path: &Path,
    config: &Config<impl Loader>,
    check_natives: bool,
    to_be_extracted: &mut Vec<vanilla::File>,
) -> crate::Result<Vec<DownloadFile>> {
    let version_jar_path = config.get_version_jar_path();
    let version_download = if !version_jar_path.exists()
        || !calculate_sha1(&version_jar_path)?.eq(&meta.downloads.client.sha1)
    {
        Some(DownloadFile {
            file_name: version_jar_path
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .to_string(),
            r#type: FileType::Library,
            path: version_jar_path,
            sha1: meta.downloads.client.sha1.clone(),
            url: meta.downloads.client.url.clone(),
        })
    } else {
        None
    };

    let asset_files = asset_index
        .objects
        .iter()
        .map(|(key, meta)| {
            let assets_path = config.get_assets_path();
            let hash = &meta.hash;
            DownloadFile {
                file_name: key.clone(),
                sha1: hash.clone(),
                url: format!("{}/{}/{}", RESOURCES_ENDPOINT, &hash[0..2], hash),
                path: assets_path.join("objects").join(&hash[0..2]).join(hash),
                r#type: FileType::Asset {
                    is_map: asset_index.map_to_resources.unwrap_or_default(),
                    is_virtual: asset_index.r#virtual.unwrap_or_default(),
                },
            }
        })
        .collect::<Vec<_>>();

    let library_files = meta
        .libraries
        .iter()
        .filter_map(|lib| {
            if !lib.rules.parse_rule() {
                return None;
            }
            let downloads = lib.downloads.as_ref()?;
            if check_natives {
                if let Some(classifiers) = &downloads.classifiers {
                    let classifier = match OS {
                        "windows" => &classifiers.natives_windows,
                        "linux" => &classifiers.natives_linux,
                        "macos" => &classifiers.natives_macos,
                        _ => return None,
                    };
                    if let Some(classifier) = classifier {
                        if let Some(classifier_path) = &classifier.path {
                            let path = config
                                .game_dir
                                .join("libraries")
                                .join(classifier_path.replace("/", MAIN_SEPARATOR_STR));
                            let url = classifier.url.clone();
                            let sha1 = classifier.sha1.clone();
                            to_be_extracted.push(vanilla::File {
                                path: Some(path.to_string_lossy().into_owned()),
                                sha1: sha1.clone(),
                                size: classifier.size,
                                url: url.clone(),
                            });
                            return Some(DownloadFile {
                                file_name: PathBuf::from(url.clone())
                                    .file_name()
                                    .unwrap_or_default()
                                    .to_string_lossy()
                                    .to_string(),
                                sha1,
                                url,
                                path,
                                r#type: FileType::Library,
                            });
                        }
                    }
                }
            }
            let artifact = downloads.artifact.as_ref()?;
            Some(DownloadFile {
                file_name: PathBuf::from(artifact.url.clone())
                    .file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string(),
                sha1: artifact.sha1.clone(),
                url: artifact.url.clone(),
                path: config
                    .game_dir
                    .join("libraries")
                    .join(artifact.path.as_ref()?.replace("/", MAIN_SEPARATOR_STR)),
                r#type: FileType::Library,
            })
        })
        .collect::<Vec<_>>();

    let java_files = java_files
        .files
        .iter()
        .filter_map(|(name, file)| {
            let path = runtime_path.join(name.replace("/", MAIN_SEPARATOR_STR));
            file.downloads.as_ref().map(|downloads| DownloadFile {
                file_name: name
                    .split(MAIN_SEPARATOR_STR)
                    .last()
                    .unwrap_or(name)
                    .to_string(),
                path,
                sha1: downloads.raw.sha1.clone(),
                url: downloads.raw.url.clone(),
                r#type: FileType::Java,
            })
        })
        .collect::<Vec<_>>();

    Ok([
        version_download.into_iter().collect::<Vec<_>>(),
        asset_files,
        library_files,
        java_files,
    ]
    .concat())
}

/// Executes any processors defined in the version metadata, if they exist.
///
/// # Parameters
/// - `meta`: The version metadata containing processor information.
/// - `config`: The configuration for the installation process.
///
/// # Returns
/// A result indicating success or failure of the processor execution.
async fn execute_processors_if_exists(
    meta: &mut VersionMeta,
    config: &Config<impl Loader>,
) -> crate::Result<()> {
    if let Some(ref mut processors) = meta.processors {
        let data = meta
            .data
            .as_ref()
            .ok_or_else(|| Error::NotFound("Forge Installer Data".to_string()))?;

        let libraries_path = config.get_libraries_path();

        for processor in processors {
            if let Some(sides) = &processor.sides {
                if !sides.contains(&"client".to_string()) {
                    continue;
                }
            }

            if processor.success {
                continue;
            }

            let classpath = processor
                .classpath
                .iter()
                .filter_map(|arg| {
                    Some(
                        libraries_path
                            .join(parse_lib_path(arg).ok()?)
                            .to_string_lossy()
                            .into_owned(),
                    )
                })
                .collect::<Vec<String>>()
                .join(CLASSPATH_SEPARATOR);

            let main_class = read_file_from_jar(
                &libraries_path
                    .join(parse_lib_path(&processor.jar)?)
                    .to_string_lossy()
                    .into_owned(),
                "META-INF/MANIFEST.MF",
            )?
            .lines()
            .find(|line| line.starts_with("Main-Class:"))
            .ok_or_else(|| Error::NotFound("Main-Class of processor".to_string()))?
            .split(":")
            .last()
            .ok_or_else(|| Error::NotFound("Main-Class of processor".to_string()))?
            .trim()
            .to_string();

            let args = processor
                .args
                .iter()
                .map(|arg| {
                    let trimmed_arg = &arg[1..arg.len() - 1];
                    if arg.starts_with('{') {
                        if let Some(entry) = data.get(trimmed_arg) {
                            if entry.client.starts_with('[') {
                                if let Ok(parsed_path) =
                                    parse_lib_path(&entry.client[1..entry.client.len() - 1])
                                {
                                    return libraries_path
                                        .join(parsed_path)
                                        .to_string_lossy()
                                        .into_owned();
                                }
                            }
                            return entry.client.clone();
                        }
                    } else if arg.starts_with('[') {
                        if let Ok(parsed_path) = parse_lib_path(trimmed_arg) {
                            return libraries_path
                                .join(parsed_path)
                                .to_string_lossy()
                                .into_owned();
                        }
                    }

                    arg.clone()
                })
                .collect::<Vec<_>>();

            let child = Command::new(
                config
                    .get_java_path(
                        meta.java_version
                            .as_ref()
                            .unwrap_or(&JavaVersion::default()),
                    )
                    .await?,
            )
            .arg("-cp")
            .arg(format!(
                "{}{}{}",
                classpath,
                CLASSPATH_SEPARATOR,
                libraries_path
                    .join(parse_lib_path(&processor.jar)?)
                    .to_string_lossy()
                    .into_owned()
            ))
            .arg(main_class)
            .args(args)
            .output()
            .await?;

            if child.status.success() {
                processor.success = true;
            } else {
                return Err(Error::Fail(format!(
                    "Processor failed: {}",
                    String::from_utf8_lossy(&child.stderr)
                )));
            }
        }
    }

    write_json(&config.get_version_json_path(), &meta).await?;

    Ok(())
}

/// Downloads the necessary files based on the provided file list.
///
/// # Parameters
/// - `files`: A vector of files to be downloaded.
/// - `game_dir`: The directory where the game is installed.
/// - `legacy`: A flag indicating whether to handle legacy assets.
/// - `emitter`: An optional emitter for logging progress.
/// - `client`: An optional HTTP client for making requests.
///
/// # Returns
/// A result indicating success or failure of the download process.
async fn download_necessary(
    files: Vec<DownloadFile>,
    game_dir: &Path,
    legacy: bool,
    emitter: Option<&Emitter>,
    client: Option<&reqwest::Client>,
) -> crate::Result<()> {
    let broken_ones: Vec<(String, PathBuf, FileType)> = files
        .par_iter()
        .filter_map(|file| {
            if file.url.is_empty() {
                return None;
            }
            if !file.path.exists()
                || (!file.sha1.is_empty() && calculate_sha1(&file.path).ok()? != file.sha1)
            {
                return Some((file.url.clone(), file.path.clone(), file.r#type.clone()));
            }
            None
        })
        .collect();

    download_multiple(broken_ones, emitter, client).await?;

    if legacy {
        files.par_iter().try_for_each(|file| {
            if let FileType::Asset { is_virtual, is_map } = file.r#type {
                let target_path = if is_virtual {
                    game_dir
                        .join("assets")
                        .join("virtual")
                        .join("legacy")
                        .join(&file.file_name)
                } else if is_map {
                    game_dir.join("resources").join(&file.file_name)
                } else {
                    return None::<()>;
                };

                if let Some(parent) = target_path.parent() {
                    if !parent.is_dir() {
                        fs::create_dir_all(parent).ok();
                    }
                }

                if !target_path.exists() || calculate_sha1(&target_path).ok()? != file.sha1 {
                    fs::copy(&file.path, &target_path).ok();
                }

                return None;
            }

            None
        });
    }

    Ok(())
}