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
use crate::consts;
use crate::error::CobbleResult;
use crate::minecraft::extract_native::extract_native;
use crate::minecraft::installation_update::{InstallationUpdate, Progress};
use crate::minecraft::models::asset_index_data::AssetIndexData;
use crate::minecraft::models::version_data::VersionData;
use crate::utils::download::download_file_check;
use crossbeam_channel::Sender;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

/// Installs all libraries as defined in the provided version data and extracts natives.
///
/// Also provides updates during installation and supports cancelling the installation.
pub fn install_libraries(
    version_data: &VersionData,
    libraries_path: impl AsRef<Path>,
    natives_path: impl AsRef<Path>,
    update_sender: Sender<InstallationUpdate>,
    cancel: Arc<AtomicBool>,
) -> CobbleResult<()> {
    debug!("Install libraries");
    trace!("Version: {}", &version_data.id);
    trace!(
        "Libraries Path: {}",
        libraries_path.as_ref().to_string_lossy()
    );
    trace!("Natives Path: {}", natives_path.as_ref().to_string_lossy());

    let needed_libraries = version_data.needed_libraries();
    let mut update_progress_template = Progress {
        total_files: needed_libraries.len(),
        ..Default::default()
    };

    for (n, library) in needed_libraries.into_iter().enumerate() {
        trace!("Library: {}", &library.name);
        let artifact = &library.downloads.artifact;

        // Check if canceled
        if cancel.load(Ordering::Relaxed) {
            trace!("Cancel installation");
            let _ = update_sender.send(InstallationUpdate::Cancel);
            return Ok(());
        }

        // Send update
        update_progress_template.current_file = n + 1;
        update_progress_template.current_file_url = artifact.url.clone();
        update_progress_template.current_file_size = Some(artifact.size);
        let _ = update_sender.send(InstallationUpdate::Library(
            update_progress_template.clone(),
        ));

        // Extract library information
        let (mut package, name, version) = library.extract_information()?;
        package = package.replace('.', "/");

        let mut library_path = PathBuf::from(libraries_path.as_ref());
        library_path.push(&package);
        library_path.push(&name);
        library_path.push(&version);

        // Create path
        fs::create_dir_all(&library_path)?;

        // Download library file
        let jar_name = format!("{}-{}.jar", name, version);
        let mut jar_path = library_path.clone();
        jar_path.push(&jar_name);

        let jar_sha = hex::decode(&artifact.sha1)?;
        download_file_check(&artifact.url, &jar_path, Some(jar_sha))?;

        // Native
        if let Some(native) = library.get_native() {
            trace!("Native: {}", &library.name);
            let native_jar_name = format!("{}-{}-{}.jar", name, version, native);
            let mut native_jar_path = library_path.clone();
            native_jar_path.push(&native_jar_name);

            let native_download_url = format!(
                "{}/{}/{}/{}/{}",
                consts::MC_LIBRARIES_BASE_URL,
                &package,
                &name,
                &version,
                &native_jar_name
            );

            // Send update
            update_progress_template.current_file_url = native_download_url.clone();
            update_progress_template.current_file_size = None;
            let _ = update_sender.send(InstallationUpdate::Library(
                update_progress_template.clone(),
            ));

            // TODO: Check SHA1
            download_file_check(&native_download_url, &native_jar_path, None)?;

            // Extract
            if let Some(extract) = &library.extract {
                extract_native(&native_jar_path, &natives_path, &extract.exclude)?;
            }
        }
    }

    Ok(())
}

/// Installs assets as defined in the asset index.
///
/// Also provides updates during installation and supports cancelling the installation.
pub fn install_assets(
    asset_index: &AssetIndexData,
    assets_path: impl AsRef<Path>,
    update_sender: Sender<InstallationUpdate>,
    cancel: Arc<AtomicBool>,
) -> CobbleResult<()> {
    debug!("Install assets");
    trace!("Assets Path: {}", assets_path.as_ref().to_string_lossy());

    let mut objects_path = PathBuf::from(assets_path.as_ref());
    objects_path.push("objects");

    let mut update_progress_template = Progress {
        total_files: asset_index.objects.len(),
        ..Default::default()
    };

    for (n, asset_info) in asset_index.objects.values().enumerate() {
        trace!("Asset: {}", &asset_info.hash);
        let hash_part: String = asset_info.hash.chars().take(2).collect();
        let asset_url = format!(
            "{}/{}/{}",
            consts::MC_ASSETS_BASE_URL,
            &hash_part,
            &asset_info.hash
        );

        // Check if canceled
        if cancel.load(Ordering::Relaxed) {
            trace!("Cancel installation");
            let _ = update_sender.send(InstallationUpdate::Cancel);
            return Ok(());
        }

        // Send update
        update_progress_template.current_file = n + 1;
        update_progress_template.current_file_url = asset_url.clone();
        update_progress_template.current_file_size = Some(asset_info.size);
        let _ = update_sender.send(InstallationUpdate::Asset(update_progress_template.clone()));

        let mut asset_path = objects_path.clone();
        asset_path.push(&hash_part);

        // Create path
        fs::create_dir_all(&asset_path)?;

        asset_path.push(&asset_info.hash);

        let asset_sha = hex::decode(&asset_info.hash)?;
        download_file_check(&asset_url, &asset_path, Some(asset_sha))?;
    }

    Ok(())
}

/// Installs assets as resources as defined in the asset index.
/// This methods needs to be used when installing older versions of minecraft.
/// The asset index provides [map_to_resources](crate::minecraft::models::asset_index_data::AssetIndexData::map_to_resources)
/// that defines if assets need to be installed as assets or resources.
///
/// Also provides updates during installation and supports cancelling the installation.
pub fn install_resources(
    asset_index: &AssetIndexData,
    resources_path: impl AsRef<Path>,
    minecraft_path: impl AsRef<Path>,
    update_sender: Sender<InstallationUpdate>,
    cancel: Arc<AtomicBool>,
) -> CobbleResult<()> {
    debug!("Install resources");
    trace!(
        "Resources Path: {}",
        resources_path.as_ref().to_string_lossy()
    );
    trace!(
        "Minecraft Path: {}",
        minecraft_path.as_ref().to_string_lossy()
    );

    let mut update_progress_template = Progress {
        total_files: asset_index.objects.len(),
        ..Default::default()
    };

    for (n, (key, asset_info)) in asset_index.objects.iter().enumerate() {
        trace!("Resource: {}", key);
        let hash_part: String = asset_info.hash.chars().take(2).collect();
        let asset_url = format!(
            "{}/{}/{}",
            consts::MC_ASSETS_BASE_URL,
            &hash_part,
            &asset_info.hash
        );

        // Check if canceled
        if cancel.load(Ordering::Relaxed) {
            trace!("Cancel installation");
            let _ = update_sender.send(InstallationUpdate::Cancel);
            return Ok(());
        }

        // Send update
        update_progress_template.current_file = n + 1;
        update_progress_template.current_file_url = asset_url.clone();
        update_progress_template.current_file_size = Some(asset_info.size);
        let _ = update_sender.send(InstallationUpdate::Asset(update_progress_template.clone()));

        // Create path
        let mut resource_path = PathBuf::from(resources_path.as_ref());
        resource_path.push(key);
        resource_path.pop();
        fs::create_dir_all(&resource_path)?;

        let mut resource_path = PathBuf::from(resources_path.as_ref());
        resource_path.push(key);

        let resource_sha = hex::decode(&asset_info.hash)?;
        download_file_check(&asset_url, &resource_path, Some(resource_sha))?;
    }

    // Create symlink
    let mut minecraft_resources_path = PathBuf::from(minecraft_path.as_ref());
    minecraft_resources_path.push("resources");
    if !minecraft_resources_path.exists() {
        trace!("Creating symlink for resources");
        symlink::symlink_dir(&resources_path, minecraft_resources_path)?;
    }

    Ok(())
}

/// Installs the log config file.
///
/// Also provides updates during installation and supports cancelling the installation.
pub fn install_log_config(
    version_data: &VersionData,
    log_configs_path: impl AsRef<Path>,
    update_sender: Sender<InstallationUpdate>,
    cancel: Arc<AtomicBool>,
) -> CobbleResult<()> {
    debug!("Install log config");
    trace!("Version: {}", &version_data.id);
    trace!(
        "Log Configs Path: {}",
        log_configs_path.as_ref().to_string_lossy()
    );

    if let Some(logging_info) = &version_data.logging {
        // Check if canceled
        if cancel.load(Ordering::Relaxed) {
            trace!("Cancel installation");
            let _ = update_sender.send(InstallationUpdate::Cancel);
            return Ok(());
        }

        // Send update
        let update_progress = Progress {
            total_files: 1,
            current_file: 1,
            current_file_url: logging_info.client.file.url.clone(),
            current_file_size: Some(logging_info.client.file.size),
        };
        let _ = update_sender.send(InstallationUpdate::LogConfig(update_progress));

        // Create path
        fs::create_dir_all(&log_configs_path)?;

        let mut config_path = PathBuf::from(log_configs_path.as_ref());
        config_path.push(
            &logging_info
                .client
                .file
                .id
                .as_ref()
                .expect("Logging info has no ID"),
        );

        let config_sha = hex::decode(&logging_info.client.file.sha1)?;
        download_file_check(
            &logging_info.client.file.url,
            &config_path,
            Some(config_sha),
        )?;
    }

    Ok(())
}

/// Installs the Minecraft client.argumentspports cancelling the installation.
pub fn install_client(
    version_data: &VersionData,
    minecraft_path: impl AsRef<Path>,
    update_sender: Sender<InstallationUpdate>,
    cancel: Arc<AtomicBool>,
) -> CobbleResult<()> {
    debug!("Install client");
    trace!("Version: {}", &version_data.id);
    trace!(
        "Minecraft Path: {}",
        minecraft_path.as_ref().to_string_lossy()
    );

    if let Some(downloads) = &version_data.downloads {
        // Check if canceled
        if cancel.load(Ordering::Relaxed) {
            trace!("Cancel installation");
            let _ = update_sender.send(InstallationUpdate::Cancel);
            return Ok(());
        }

        // Send update
        let update_progress = Progress {
            total_files: 1,
            current_file: 1,
            current_file_url: downloads.client.url.clone(),
            current_file_size: Some(downloads.client.size),
        };
        let _ = update_sender.send(InstallationUpdate::Client(update_progress));

        let mut minecraft_path = PathBuf::from(minecraft_path.as_ref());
        minecraft_path.push("bin");

        // Create path
        fs::create_dir_all(&minecraft_path)?;

        minecraft_path.push(format!("minecraft-{}-client.jar", &version_data.id));

        let client_sha = hex::decode(&downloads.client.sha1)?;
        download_file_check(&downloads.client.url, &minecraft_path, Some(client_sha))?;
    }

    Ok(())
}