summaryrefslogtreecommitdiffstats
path: root/src/version.rs
blob: 188b88a0732d1ad1bc48baf2b14371982538bd19 (plain) (blame)
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
use core::fmt;
use std::{collections::BTreeMap, convert::Infallible, marker::PhantomData, ops::Deref, str::FromStr};
use std::collections::HashMap;
use chrono::{DateTime, Utc};
use regex::Regex;
use serde::{de::{self, Visitor}, Deserialize, Deserializer};
use serde::de::SeqAccess;
use sha1_smol::Digest;

pub mod manifest;
use manifest::*;

#[derive(Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "lowercase")]
pub enum RuleAction {
    Allow,
    Disallow
}

// must derive an order on this because it's used as a key for a btreemap
#[derive(Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
#[serde(rename_all = "lowercase")]
pub enum OperatingSystem {
    Linux,   // "linux"
    Windows, // "windows"

    #[serde(alias = "osx")] // not technically correct but it works
    MacOS,   // "osx"

    #[serde(other)]
    Unknown  // (not used in official jsons)
}

#[derive(Debug, Clone)]
struct WrappedRegex(Regex);

impl Deref for WrappedRegex {
    type Target = Regex;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

struct RegexVisitor;
impl<'de> Visitor<'de> for RegexVisitor {
    type Value = WrappedRegex;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a valid regular expression")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: de::Error, {
        Regex::new(v).map_err(de::Error::custom).map(|r| WrappedRegex(r))
    }
}

impl<'de> Deserialize<'de> for WrappedRegex {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de> {
        deserializer.deserialize_any(RegexVisitor)
    }
}

#[derive(Deserialize, Debug, Clone)]
pub struct OSRestriction {
    pub name: Option<OperatingSystem>,

    pub version: Option<WrappedRegex>,
    pub arch: Option<WrappedRegex>
}

#[derive(Deserialize, Debug, Clone)]
pub struct CompatibilityRule {
    pub action: RuleAction,
    pub features: Option<BTreeMap<String, bool>>,
    pub os: Option<OSRestriction>
}

impl CompatibilityRule {
    pub fn features_match(&self, checker: fn(&str) -> bool) -> bool {
        if let Some(m) = self.features.as_ref() {
            for (feat, expect) in m {
                if checker(feat) != *expect {
                    return false;
                }
            }
        }

        true
    }
}

#[derive(Deserialize, Debug, Clone)]
pub struct Argument {
    #[serde(default)]
    pub rules: Option<Vec<CompatibilityRule>>,

    #[serde(default)]
    #[serde(deserialize_with = "string_or_array")]
    pub value: Vec<String>
}

#[derive(Debug, Clone)]
pub struct WrappedArgument(Argument);

impl FromStr for Argument {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Argument {
            value: vec![s.to_owned()],
            rules: None
        })
    }
}

impl Deref for WrappedArgument {
    type Target = Argument;
    
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'de> Deserialize<'de> for WrappedArgument {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de> {
        Ok(WrappedArgument(string_or_struct(deserializer)?))
    }
}

#[derive(Deserialize, Debug, Clone)]
pub struct Arguments {
    pub game: Option<Vec<WrappedArgument>>,
    pub jvm: Option<Vec<WrappedArgument>>
}

impl Arguments {
    fn apply_child(&mut self, other: &Arguments) {
        if self.game.is_none() {
            if let Some(game) = other.game.as_ref() {
                self.game.replace(game.to_owned());
            }
        }

        if self.jvm.is_none() {
            if let Some(jvm) = other.jvm.as_ref() {
                self.jvm.replace(jvm.to_owned());
            }
        }
    }
}

#[derive(Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum DownloadType {
    Client,
    ClientMappings,
    Server,
    ServerMappings,
    WindowsServer
}

#[derive(Deserialize, Debug, Clone)]
pub struct DownloadInfo {
    pub sha1: Option<Digest>,
    pub size: Option<usize>,
    pub total_size: Option<usize>, // available for asset index
    pub url: Option<String>, // may not be present for libraries
    pub id: Option<String>,
    pub path: Option<String>
}

#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct JavaVersionInfo {
    pub component: String,
    pub major_version: u32
}

#[derive(Deserialize, Debug, Clone)]
pub struct LibraryDownloads {
    pub artifact: Option<DownloadInfo>,
    pub classifiers: Option<BTreeMap<String, DownloadInfo>>
}

#[derive(Deserialize, Debug, Clone)]
pub struct LibraryExtractRule {
    #[serde(default)]
    pub exclude: Vec<String>
}

#[derive(Deserialize, Debug, Clone)]
pub struct Library {
    pub downloads: Option<LibraryDownloads>,
    pub name: String,
    pub extract: Option<LibraryExtractRule>,
    pub natives: Option<BTreeMap<OperatingSystem, String>>,
    pub rules: Option<Vec<CompatibilityRule>>,
    pub url: Option<String> // old format
}

#[derive(Deserialize, Debug, Clone)]
pub struct ClientLogging {
    pub argument: String,

    #[serde(rename = "type")]
    pub logger_type: String,
    pub file: DownloadInfo
}

#[derive(Deserialize, Debug, Clone)]
pub struct Logging {
    pub client: ClientLogging // other fields unknown
}

#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CompleteVersion {
    pub arguments: Option<Arguments>,
    pub minecraft_arguments: Option<String>,

    pub asset_index: Option<DownloadInfo>,
    pub assets: Option<String>,

    pub compliance_level: Option<u32>,

    pub java_version: Option<JavaVersionInfo>,

    #[serde(default)]
    pub downloads: BTreeMap<DownloadType, DownloadInfo>,

    #[serde(default, deserialize_with = "deserialize_libraries")]
    pub libraries: HashMap<String, Library>,

    pub id: String,
    pub jar: Option<String>, // used as the jar filename if specified? (no longer used officially)
    
    pub logging: Option<Logging>,

    pub main_class: Option<String>,
    pub minimum_launcher_version: Option<u32>,
    pub release_time: Option<DateTime<Utc>>,
    pub time: Option<DateTime<Utc>>,

    #[serde(rename = "type")]
    pub version_type: Option<VersionType>,

    pub compatibility_rules: Option<Vec<CompatibilityRule>>, //
    pub incompatibility_reason: Option<String>, // message shown when compatibility rules fail for this version

    pub inherits_from: Option<String>

    /* omitting field `savableVersion' because it seems like a vestigial part from old launcher versions
     * (also it isn't even a string that is present in modern liblauncher.so, so I assume it will never be used.)
     */
}

impl CompleteVersion {
    pub fn get_jar(&self) -> &String {
        &self.jar.as_ref().unwrap_or(&self.id)
    }

    pub fn apply_child(&mut self, other: &CompleteVersion) {
        macro_rules! replace_missing {
            ($name:ident) => {
                if self.$name.is_none() {
                    if let Some($name) = other.$name.as_ref() {
                        self.$name.replace($name.to_owned());
                    }
                }
            };
        }

        if let Some(arguments) = other.arguments.as_ref() {
            if let Some(my_args) = self.arguments.as_mut() {
                my_args.apply_child(arguments);
            } else {
                self.arguments.replace(arguments.to_owned());
            }
        }

        replace_missing!(minecraft_arguments);
        replace_missing!(asset_index);
        replace_missing!(assets);
        replace_missing!(compliance_level);
        replace_missing!(java_version);

        for (dltype, dl) in other.downloads.iter().by_ref() {
            self.downloads.entry(*dltype).or_insert_with(|| dl.clone());
        }

        for (name, lib) in other.libraries.iter().by_ref() {
            self.libraries.entry(name.to_owned()).or_insert_with(|| lib.clone());
        }

        replace_missing!(logging);
        replace_missing!(main_class);
        replace_missing!(minimum_launcher_version);
        replace_missing!(release_time);
        replace_missing!(time);
        replace_missing!(version_type);

        if let Some(rules) = other.compatibility_rules.as_ref() {
            if let Some(my_rules) = self.compatibility_rules.as_mut() {
                for rule in rules {
                    my_rules.push(rule.to_owned());
                }
            } else {
                self.compatibility_rules.replace(rules.to_owned());
            }
        }

        replace_missing!(incompatibility_reason);
    }
}

fn canonicalize_library_name(name: &str) -> String {
    name.split(':')
        .enumerate()
        .filter(|(i, _)| *i != 2)
        .map(|(_, s)| s.to_ascii_lowercase())
        .collect::<Vec<_>>()
        .join(":")
}

fn deserialize_libraries<'de, D>(deserializer: D) -> Result<HashMap<String, Library>, D::Error>
where
    D: Deserializer<'de>
{
    struct LibrariesVisitor;

    impl<'de> Visitor<'de> for LibrariesVisitor {
        type Value = HashMap<String, Library>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("an array of libraries")
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let mut map = HashMap::new();

            while let Some(lib) = seq.next_element::<Library>()? {
                map.insert(canonicalize_library_name(lib.name.as_str()), lib);
            }

            Ok(map)
        }
    }

    deserializer.deserialize_seq(LibrariesVisitor)
}

// https://serde.rs/string-or-struct.html
fn string_or_struct<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
    T: Deserialize<'de> + FromStr<Err = Infallible>,
    D: Deserializer<'de>,
{
    struct StringOrStruct<T>(PhantomData<fn() -> T>);

    impl<'de, T> Visitor<'de> for StringOrStruct<T>
    where
        T: Deserialize<'de> + FromStr<Err = Infallible>,
    {
        type Value = T;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("string or map")
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: de::Error, {
            Ok(FromStr::from_str(v).unwrap())
        }

        fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
            where
                A: de::MapAccess<'de>, {
            // wizardry (check comment in link)
            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
        }
    }

    deserializer.deserialize_any(StringOrStruct(PhantomData))
}

// adapted from above
fn string_or_array<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
where
    T: Deserialize<'de> + FromStr<Err = Infallible>,
    D: Deserializer<'de>,
{
    struct StringOrVec<T>(PhantomData<fn() -> T>);

    impl<'de, T> Visitor<'de> for StringOrVec<T>
    where
        T: Deserialize<'de> + FromStr<Err = Infallible>,
    {
        type Value = Vec<T>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("string or array")
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: de::Error, {
            Ok(vec![FromStr::from_str(v).unwrap()])
        }

        fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>, {
            Deserialize::deserialize(de::value::SeqAccessDeserializer::new(seq))
        }
    }

    deserializer.deserialize_any(StringOrVec(PhantomData))
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::*;

    #[test]
    fn test_it() {
        let s = fs::read_to_string("./test_stuff/versions/1.7.10.json");

        let arg: CompleteVersion = serde_json::from_str(s.unwrap().as_str()).unwrap();
        dbg!(arg);
    }
    
    #[test]
    fn test_it2() {
        let s = fs::read_to_string("./test_stuff/version_manifest_v2.json");

        let arg: VersionManifest = serde_json::from_str(s.unwrap().as_str()).unwrap();
        dbg!(arg);
    }

    #[test]
    fn test_it3() {
        assert_eq!(canonicalize_library_name("group:artifact:version"), String::from("group:artifact"));
        assert_eq!(canonicalize_library_name("group:artifact:version:specifier"), String::from("group:artifact:specifier"));
        assert_eq!(canonicalize_library_name("not_enough:fields"), String::from("not_enough:fields"));
        assert_eq!(canonicalize_library_name("word"), String::from("word"));
        assert_eq!(canonicalize_library_name(""), String::from(""));
    }
}