libium 1.29.0

Multi-source backend for managing Minecraft mods and modpacks from Modrinth, CurseForge, and Github Releases
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
use crate::{
    config::structs::{Mod, ModIdentifier, ModIdentifierRef, ModLoader, Profile},
    upgrade::check::{self, game_version_check, mod_loader_check},
    APIs,
};
use serde::Deserialize;
use std::{collections::HashMap, str::FromStr};

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error(
        "The developer of this project has denied third party applications from downloading it"
    )]
    /// The user can manually download the mod and place it in the `user` folder of the output directory to mitigate this.
    /// However, they will have to manually update the mod.
    DistributionDenied,
    #[error("The project has already been added")]
    AlreadyAdded,
    #[error("The project is not compatible")]
    Incompatible,
    #[error("The project does not exist")]
    DoesNotExist,
    #[error("The project is not a mod")]
    NotAMod,
    #[error("GitHub: {0}")]
    GitHubError(String),
    #[error("GitHub: {0:#?}")]
    OctocrabError(#[from] octocrab::Error),
    #[error("Modrinth: {0}")]
    ModrinthError(#[from] ferinth::Error),
    #[error("CurseForge: {0}")]
    CurseForgeError(#[from] furse::Error),
}
type Result<T> = std::result::Result<T, Error>;

#[derive(Deserialize, Debug)]
struct GraphQlResponse {
    data: HashMap<String, Option<ResponseData>>,
    #[serde(default)]
    errors: Vec<GraphQLError>,
}

#[derive(Deserialize, Debug)]
struct GraphQLError {
    #[serde(rename = "type")]
    type_: String,
    path: Vec<String>,
    message: String,
}

#[derive(Deserialize, Debug)]
struct ResponseData {
    owner: OwnerData,
    name: String,
    releases: ReleaseConnection,
}
#[derive(Deserialize, Debug)]
struct OwnerData {
    login: String,
}
#[derive(Deserialize, Debug)]
struct ReleaseConnection {
    nodes: Vec<Release>,
}
#[derive(Deserialize, Debug)]
struct Release {
    #[serde(rename = "releaseAssets")]
    assets: ReleaseAssetConnection,
}
#[derive(Deserialize, Debug)]
struct ReleaseAssetConnection {
    nodes: Vec<ReleaseAsset>,
}
#[derive(Deserialize, Debug)]
struct ReleaseAsset {
    name: String,
}

pub fn parse_id(id: String) -> ModIdentifier {
    if let Ok(id) = id.parse() {
        ModIdentifier::CurseForgeProject(id)
    } else {
        let split = id.split('/').collect::<Vec<_>>();
        if split.len() == 2 {
            ModIdentifier::GitHubRepository((split[0].to_owned(), split[1].to_owned()))
        } else {
            ModIdentifier::ModrinthProject(id)
        }
    }
}

/// Classify the `identifiers` into the appropriate platforms, send batch requests to get the necessary information,
/// check details about the projects, and add them to `profile` if suitable.
/// Performs checks on the mods to see whether they're compatible with the profile if `perform_checks` is true
pub async fn add(
    apis: APIs<'_>,
    profile: &mut Profile,
    identifiers: Vec<ModIdentifier>,
    perform_checks: bool,
    check_game_version: bool,
    check_mod_loader: bool,
) -> Result<(Vec<String>, Vec<(String, Error)>)> {
    let mut mr_ids = Vec::new();
    let mut cf_ids = Vec::new();
    let mut gh_ids = Vec::new();
    let mut errors = Vec::new();

    for id in identifiers {
        match id {
            ModIdentifier::CurseForgeProject(id) => cf_ids.push(id),
            ModIdentifier::ModrinthProject(id) => mr_ids.push(id),
            ModIdentifier::GitHubRepository(id) => gh_ids.push(id),
        }
    }

    let cf_projects = if !cf_ids.is_empty() {
        cf_ids.sort_unstable();
        cf_ids.dedup();
        apis.cf.get_mods(cf_ids.clone()).await?
    } else {
        Vec::new()
    };

    let mr_projects = if !mr_ids.is_empty() {
        mr_ids.sort_unstable();
        mr_ids.dedup();
        apis.mr
            .get_multiple_projects(&mr_ids.iter().map(AsRef::as_ref).collect::<Vec<_>>())
            .await?
    } else {
        Vec::new()
    };

    let gh_repos = {
        // Construct GraphQl query using raw strings
        let mut graphql_query = "{".to_string();
        for (i, (owner, name)) in gh_ids.iter().enumerate() {
            graphql_query.push_str(&format!(
                "_{i}: repository(owner: \"{owner}\", name: \"{name}\") {{
                    owner {{
                        login
                    }}
                    name
                    releases(first: 100) {{
                      nodes {{
                        releaseAssets(first: 10) {{
                          nodes {{
                            name
                          }}
                        }}
                      }}
                    }}
                }}"
            ));
        }
        graphql_query.push('}');

        // Send the query
        let response: GraphQlResponse = if !gh_ids.is_empty() {
            apis.gh
                .graphql(&HashMap::from([("query", graphql_query)]))
                .await?
        } else {
            GraphQlResponse {
                data: HashMap::new(),
                errors: Vec::new(),
            }
        };

        errors.extend(response.errors.into_iter().map(|v| {
            (
                {
                    let id = &gh_ids[v.path[0]
                        .strip_prefix('_')
                        .and_then(|s| s.parse::<usize>().ok())
                        .expect("Unexpected response data")];
                    format!("{}/{}", id.0, id.1)
                },
                if v.type_ == "NOT_FOUND" {
                    Error::DoesNotExist
                } else {
                    Error::GitHubError(v.message)
                },
            )
        }));

        response
            .data
            .into_values()
            .flatten()
            .map(|d| {
                (
                    (d.owner.login, d.name),
                    d.releases
                        .nodes
                        .into_iter()
                        .flat_map(|r| r.assets.nodes.into_iter().map(|e| e.name))
                        .collect::<Vec<_>>(),
                )
            })
            .collect::<Vec<_>>()
    };

    let mut success_names = Vec::new();

    for project in cf_projects {
        if let Some(i) = cf_ids.iter().position(|&id| id == project.id) {
            cf_ids.swap_remove(i);
        }

        match curseforge(
            &project,
            profile,
            perform_checks,
            check_game_version,
            check_mod_loader,
        ) {
            Ok(_) => success_names.push(project.name),
            Err(err) => errors.push((format!("{} ({})", project.name, project.id), err)),
        }
    }
    errors.extend(
        cf_ids
            .iter()
            .map(|id| (id.to_string(), Error::DoesNotExist)),
    );

    for project in mr_projects {
        if let Some(i) = mr_ids
            .iter()
            .position(|id| id == &project.id || project.slug.eq_ignore_ascii_case(id))
        {
            mr_ids.swap_remove(i);
        }

        match modrinth(
            &project,
            profile,
            perform_checks,
            check_game_version,
            check_mod_loader,
        ) {
            Ok(_) => success_names.push(project.title),
            Err(err) => errors.push((format!("{} ({})", project.title, project.id), err)),
        }
    }
    errors.extend(
        mr_ids
            .iter()
            .map(|id| (id.to_string(), Error::DoesNotExist)),
    );

    for (repo, asset_names) in gh_repos {
        match github(
            &repo,
            profile,
            Some(&asset_names),
            check_game_version,
            check_mod_loader,
        ) {
            Ok(_) => success_names.push(format!("{}/{}", repo.0, repo.1)),
            Err(err) => errors.push((format!("{}/{}", repo.0, repo.1), err)),
        }
    }

    Ok((success_names, errors))
}

/// Check if the repo of `repo_handler` exists, releases mods, and is compatible with `profile`.
/// If so, add it to the `profile`.
///
/// Returns the name of the repository to display to the user
pub fn github(
    id: &(impl AsRef<str> + ToString, impl AsRef<str> + ToString),
    profile: &mut Profile,
    perform_checks: Option<&[String]>,
    check_game_version: bool,
    check_mod_loader: bool,
) -> Result<()> {
    // Check if project has already been added
    if profile.mods.iter().any(|mod_| {
        mod_.name.eq_ignore_ascii_case(id.1.as_ref())
            || ModIdentifierRef::GitHubRepository((id.0.as_ref(), id.1.as_ref()))
                == mod_.identifier.as_ref()
    }) {
        return Err(Error::AlreadyAdded);
    }

    if let Some(asset_names) = perform_checks {
        // Check if jar files are released
        if !asset_names.iter().any(|name| name.ends_with(".jar")) {
            return Err(Error::NotAMod);
        }

        // Check if the repo is compatible
        check::github(
            asset_names,
            profile.get_version(check_game_version),
            profile.get_loader(check_game_version),
        )
        .ok_or(Error::Incompatible)?;
    }

    // Add it to the profile
    profile.mods.push(Mod {
        name: id.1.as_ref().trim().to_string(),
        identifier: ModIdentifier::GitHubRepository((id.0.to_string(), id.1.to_string())),
        check_game_version,
        check_mod_loader,
    });

    Ok(())
}

use ferinth::structures::project::{Project, ProjectType};

/// Check if the project of `project_id` has not already been added, is a mod, and is compatible with `profile`.
/// If so, add it to the `profile`.
pub fn modrinth(
    project: &Project,
    profile: &mut Profile,
    perform_checks: bool,
    check_game_version: bool,
    check_mod_loader: bool,
) -> Result<()> {
    // Check if project has already been added
    if profile.mods.iter().any(|mod_| {
        mod_.name.eq_ignore_ascii_case(&project.title)
            || ModIdentifierRef::ModrinthProject(&project.id) == mod_.identifier.as_ref()
    }) {
        Err(Error::AlreadyAdded)

    // Check if the project is a mod
    } else if project.project_type != ProjectType::Mod {
        Err(Error::NotAMod)

    // Check if the project is compatible
    } else if !perform_checks // Short circuit if the checks should not be performed
        || (
            game_version_check(
                profile.get_version(check_game_version).as_ref(),
                &project.game_versions,
            ) && (
                mod_loader_check(
                    profile.get_loader(check_mod_loader),
                    &project.loaders
                ) || (
                // Fabric backwards compatibility in Quilt
                profile.mod_loader == ModLoader::Quilt
                    && mod_loader_check(Some(ModLoader::Fabric), &project.loaders)
                )
            )
        )
    {
        // Add it to the profile
        profile.mods.push(Mod {
            name: project.title.trim().to_owned(),
            identifier: ModIdentifier::ModrinthProject(project.id.clone()),
            check_game_version,
            check_mod_loader,
        });

        Ok(())
    } else {
        Err(Error::Incompatible)
    }
}

/// Check if the mod of `project_id` has not already been added, is a mod, and is compatible with `profile`.
/// If so, add it to the `profile`.
pub fn curseforge(
    project: &furse::structures::mod_structs::Mod,
    profile: &mut Profile,
    perform_checks: bool,
    check_game_version: bool,
    check_mod_loader: bool,
) -> Result<()> {
    // Check if project has already been added
    if profile.mods.iter().any(|mod_| {
        mod_.name.eq_ignore_ascii_case(&project.name)
            || ModIdentifier::CurseForgeProject(project.id) == mod_.identifier
    }) {
        Err(Error::AlreadyAdded)

    // Check if it can be downloaded by third-parties
    } else if Some(false) == project.allow_mod_distribution {
        Err(Error::DistributionDenied)

    // Check if the project is a Minecraft mod
    } else if !project.links.website_url.as_str().contains("mc-mods") {
        Err(Error::NotAMod)

    // Check if the mod is compatible
    } else if !perform_checks // Short-circuit if checks do not have to be performed

        // Extract game version and loader pairs from the 'latest files',
        // which generally exist for every supported game version and loader combination
        || {
            let version = profile.get_version(check_game_version);
            let loader = profile.get_loader(check_mod_loader);
            project
                .latest_files_indexes
                .iter()
                .map(|f| {
                    (
                        &f.game_version,
                        f.mod_loader
                            .as_ref()
                            .and_then(|l| ModLoader::from_str(&format!("{:?}", l)).ok()),
                    )
                })
                .any(|p| {
                    (version.is_none() || version == Some(p.0)) &&
                    (loader.is_none() || loader == p.1)
                })
        }
    {
        profile.mods.push(Mod {
            name: project.name.trim().to_string(),
            identifier: ModIdentifier::CurseForgeProject(project.id),
            check_game_version,
            check_mod_loader,
        });

        Ok(())
    } else {
        Err(Error::Incompatible)
    }
}