summaryrefslogtreecommitdiffstats
path: root/ozone-cli/src/main.rs
blob: 11349c81941e45f2a5b6dca5a8e57efba86d0f1a (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
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
mod cli;

use std::error::Error;
use std::path::Path;
use std::process::ExitCode;
use log::{error, info, trace};
use clap::Parser;
use ozone::launcher::{Instance, JavaRuntimeSetting, Launcher, Settings, ALT_CLIENT_ID, MAIN_CLIENT_ID};
use ozone::launcher::version::{VersionList, VersionResult};
use uuid::Uuid;
use ozone::auth::{Account, AccountStorage, MsaAccount};
use ozone::auth::error::AuthErrorKind;
use crate::cli::{AccountCommand, Cli, InstanceCommand, ProfileSelectArgs, RootCommand};

const ACCOUNT_DB_PATH: &str = "ozone_accounts.json";

fn find_account<'a>(auth: &'a AccountStorage, input: &ProfileSelectArgs) -> Result<Vec<(&'a String, &'a Account)>, ()> {
    if let Some(uuid) = input.uuid {
        Ok(auth.iter_accounts().filter(|(_, a)| match *a {
            Account::Dummy(p) => p.id == uuid,
            Account::MSA(account) => account.player_profile.as_ref().is_some_and(|p| p.id == uuid)
        }).collect())
    } else if let Some(ref name) = input.name {
        let name = name.to_ascii_lowercase();

        Ok(auth.iter_accounts().filter(|(_, a)| match *a {
            Account::Dummy(profile) => profile.name.to_ascii_lowercase().starts_with(&name),
            Account::MSA(account) =>
                account.player_profile.as_ref().is_some_and(|p| p.name.to_ascii_lowercase().starts_with(&name))
        }).collect())
    } else if let Some(ref gt) = input.gamertag {
        let gt = gt.to_ascii_lowercase();

        Ok(auth.iter_accounts().filter(|(_, a)| match *a {
            Account::MSA(account) => account.gamertag.as_ref().is_some_and(|g| g.to_ascii_lowercase().starts_with(&gt)),
            _ => false
        }).collect())
    } else if let Some(ref xuid) = input.xuid {
        Ok(auth.iter_accounts().filter(|(_, a)| match *a {
            Account::MSA(account) => account.xuid.as_ref().is_some_and(|x| x == xuid),
            _ => false
        }).collect())
    } else {
        eprintln!("No account specified.");
        Err(())
    }
}

fn display_instance(instance: &Instance, id: Uuid, home: impl AsRef<Path>, selected: bool, verbose: bool) {
    println!("Instance `{}':{}", instance.name, if selected { " (selected)" } else { "" });
    println!("  UUID: {}", id);
    println!("  Version: {}", instance.game_version);
    println!("  Location: {}", home.as_ref().join(Settings::get_instance_path(id)).display());

    if !verbose { return; }

    if let Some(ref args) = instance.jvm_arguments {
        println!("  JVM arguments: <{} argument{}>", args.len(), if args.len() == 1 { "" } else { "s" })
    }

    if let Some(res) = instance.resolution {
        println!("  Resolution: {}x{}", res.width, res.height);
    }

    match &instance.java_runtime {
        Some(JavaRuntimeSetting::Component(c)) => println!("  Java runtime component: {c}"),
        Some(JavaRuntimeSetting::Path(p)) => println!("  Java runtime path: {}", p.display()),
        _ => ()
    }
}

fn display_account(account: &Account, selected: bool, verbose: bool) {
    let selected = if selected { " (selected)" } else { "" };

    match *account {
        Account::Dummy(ref profile) => {
            println!("Dummy account:{selected}");
            println!("  Username: {}", profile.name);
            println!("  UUID: {}", profile.id);
            if verbose {
                println!("  Properties: <{} propert{}>", profile.properties.len(), if profile.properties.len() == 1 { "y" } else { "ies" });
            }
        },
        Account::MSA(ref msa_acct) => {
            println!("Microsoft account:{selected}");

            if let Some(ref profile) = msa_acct.player_profile {
                println!("  Username: {}", profile.name);
                println!("  UUID: {}", profile.id);

                if verbose {
                    println!("  Properties: <{} propert{}>", profile.properties.len(), if profile.properties.len() == 1 { "y" } else { "ies" });
                }
            } else {
                println!("  Username: <no profile>");
                println!("  UUID: <no profile>");

                if verbose {
                    println!("  Properties: <no profile>");
                }
            }

            println!("  Xbox Gamertag: {}", msa_acct.gamertag.as_deref().unwrap_or("<unknown>"));
            if verbose {
                println!("  XUID: {}", msa_acct.xuid.as_deref().unwrap_or("<unknown>"));
            }
        }
    }
}

async fn main_inner(cli: Cli) -> Result<ExitCode, Box<dyn Error>> {
    let Some(home) = cli.home.or_else(Launcher::sensible_home) else {
        error!("Could not choose a launcher home directory. Please choose one with `--home'.");
        return Ok(ExitCode::FAILURE); // we print our own error message
    };

    trace!("Sensible home could be {home:?}");
    let mut settings = Settings::load(home.join("ozone.json")).await?;

    match &cli.subcmd {
        RootCommand::Instance(inst_args) => match inst_args.command() {
            InstanceCommand::List => {
                let mut first = true;

                if settings.instances.is_empty() {
                    eprintln!("There are no instances. Create one with `instance create <name>'.");
                    return Ok(ExitCode::SUCCESS);
                }

                for (cur_id, instance) in settings.instances.iter() {
                    if !first {
                        println!();
                    }

                    first = false;

                    let cur_id = *cur_id;
                    let sel = settings.selected_instance.is_some_and(|id| id == cur_id);
                    display_instance(instance, cur_id, &home, sel, false);
                }
            },
            InstanceCommand::Create(args) => {
                if args.name.is_empty() {
                    eprintln!("The instance must not have an empty name.");
                    return Ok(ExitCode::FAILURE);
                }

                let mut inst = if args.clone {
                    if let Some(selected_inst) = settings.get_selected_instance() {
                        let mut inst = selected_inst.clone();
                        inst.name.replace_range(.., &args.name);
                        inst
                    } else {
                        eprintln!("You do not have an instance selected.");
                        return Ok(ExitCode::FAILURE);
                    }
                } else {
                    Instance::new(&args.name)
                };

                if let Some(ref ver_name) = args.settings.version {
                    // FIXME: don't hardcode "versions" path
                    let versions = VersionList::new(home.join("versions"), !cli.offline).await?;
                    if matches!(versions.get_version_lazy(ver_name), VersionResult::None) {
                        eprintln!("The version `{}' could not be found.", ver_name);
                        return Ok(ExitCode::FAILURE);
                    }
                }
                
                args.settings.apply_to(&mut inst);

                let new_id = Uuid::new_v4();
                settings.instances.insert(new_id, inst);
                
                if !args.no_select {
                    settings.selected_instance = Some(new_id);
                }

                settings.save().await?;
            },
            InstanceCommand::Select(args) => {
                if let Ok(uuid) = args.instance.parse::<Uuid>() {
                    if !settings.instances.contains_key(&uuid) {
                        eprintln!("No instances were found by that UUID.");
                        return Ok(ExitCode::FAILURE);
                    }

                    settings.selected_instance = Some(uuid);
                    settings.save().await?;

                    return Ok(ExitCode::SUCCESS);
                }

                let search_norm = args.instance.to_lowercase();

                let found: Vec<_> = settings.instances.iter()
                    .filter(|(_, inst)| {
                        // FIXME: find a better way of doing this matching
                        inst.name.to_lowercase().starts_with(&search_norm)
                    }).collect();

                if found.is_empty() {
                    eprintln!("No instances were found.");
                    return Ok(ExitCode::FAILURE);
                }

                if found.len() > 1 {
                    eprintln!("Ambiguous argument. Found {} instances:", found.len());
                    for (id, inst) in found {
                        eprintln!("- {} ({id})", inst.name);
                    }

                    return Ok(ExitCode::FAILURE);
                }

                let (found_id, found_inst) = found.first().unwrap();
                println!("Selected instance {} ({found_id}).", found_inst.name);

                settings.selected_instance = Some(**found_id);
                settings.save().await?;
            },
            InstanceCommand::Set(args) => {
                let Some(inst) = settings.get_selected_instance_mut() else {
                    eprintln!("No instance selected.");
                    return Ok(ExitCode::FAILURE);
                };

                args.apply_to(inst);
                settings.save().await?;
            },
            InstanceCommand::Delete => {
                let Some(inst) = settings.selected_instance else {
                    eprintln!("No instance selected.");
                    return Ok(ExitCode::FAILURE);
                };
                
                // TODO: maybe delete the files

                settings.instances.remove(&inst);
                settings.selected_instance = None;
                settings.save().await?;
            },
            InstanceCommand::Info => {
                let Some(inst) = settings.get_selected_instance() else {
                    eprintln!("No instance selected.");
                    return Ok(ExitCode::FAILURE);
                };
                
                display_instance(inst, settings.selected_instance.unwrap(), &home, false, true);
            },
            InstanceCommand::Rename { name } => {
                if name.is_empty() {
                    eprintln!("The instance must not have an empty name.");
                    return Ok(ExitCode::FAILURE);
                }

                let Some(inst) = settings.get_selected_instance_mut() else {
                    eprintln!("No instance selected.");
                    return Ok(ExitCode::FAILURE);
                };

                inst.name.replace_range(.., name);
                settings.save().await?;
            }
        },
        RootCommand::Account(account_args) => {
            let accounts_path = home.join(ACCOUNT_DB_PATH);
            let mut accounts = AccountStorage::load(&accounts_path).await?;

            match &account_args.command {
                AccountCommand::Select(args) => {
                    let Ok(results) = find_account(&accounts, args) else {
                        return Ok(ExitCode::FAILURE);
                    };
                    
                    if results.is_empty() {
                        eprintln!("No account was found.");
                        return Ok(ExitCode::FAILURE);
                    }
                    
                    if results.len() > 1 {
                        eprintln!("Ambiguous argument. Found {} accounts:", results.len());
                        for (_, account) in results {
                            eprintln!("- {account}");
                        }
                        return Ok(ExitCode::FAILURE);
                    }

                    let (key, account) = results.into_iter().next().unwrap();
                    println!("Selected account: {account}");
                    let key = key.clone();

                    accounts.set_selected_account(key);
                    accounts.save(&accounts_path).await?;
                },
                AccountCommand::Forget => {
                    if accounts.pop_selected_account().is_none() {
                        eprintln!("No account selected.");
                        return Ok(ExitCode::FAILURE);
                    }

                    accounts.save(&accounts_path).await?;
                },
                AccountCommand::SignIn(args) => {
                    if cli.offline {
                        eprintln!("This command cannot be used while offline.");
                        return Ok(ExitCode::FAILURE);
                    }

                    let (client_id, azure) = if args.use_alt_client_id {
                        (ALT_CLIENT_ID, false)
                    } else {
                        (MAIN_CLIENT_ID, true)
                    };

                    let client = MsaAccount::create_client();

                    let mut acct = MsaAccount::with_client_id(client_id, azure);
                    acct.xbl_login_device(&client, |d| async move {
                        if let Some(uri_complete) = d.verification_uri_complete() {
                            println!("In a browser, please navigate to the following URL:");
                            println!("{}", uri_complete.secret());
                        } else {
                            println!("In a browser, please navigate to the following URL: {}", d.verification_uri());
                            println!("Use the following device code: {}", d.user_code().secret())
                        }
                    }).await?;

                    println!("Authentication success! Logging in...");

                    match acct.log_in_silent(&client).await {
                        Ok(_) => (),
                        Err(e) => match e.kind() {
                            AuthErrorKind::NotOnXbox => {
                                eprintln!("This Microsoft account is not on Xbox. Please make sure you are using the correct Microsoft account.");
                                return Ok(ExitCode::FAILURE);
                            },
                            AuthErrorKind::TooYoung => {
                                eprintln!("Currently, Microsoft accounts held by minors (under 18 years old) cannot sign into third party applications (such as olauncher) unless they are in a family.");
                                eprintln!("If you do not wish to configure a family, try running this command with the `--use-alt-client-id' flag.");
                                return Ok(ExitCode::FAILURE);
                            },
                            AuthErrorKind::NotEntitled => {
                                eprintln!("Warning: This Microsoft account does not seem to own the game.");
                                eprintln!("This account will only be able to play the demo version of the game.");
                            },
                            AuthErrorKind::NoProfile => {
                                eprintln!("Warning: It appears that you own the game but have not yet created a profile.");
                                eprintln!("Visit https://minecraft.net to choose a name. Until then, you will only be able to play the demo version of the game.");
                            },
                            _ => {
                                eprintln!("An unknown error occurred while signing into the account:");
                                eprintln!("{e}");
                                return Ok(ExitCode::FAILURE);
                            }
                        }
                    }

                    let key = accounts.add_account(acct.into()).expect("authentication succeeded but xuid missing????");
                    if !args.no_select {
                        accounts.set_selected_account(key);
                    }

                    accounts.save(&accounts_path).await?;

                    println!("Success! Account added.");
                },
                AccountCommand::List => {
                    let iter = accounts.iter_accounts();
                    if iter.len() == 0 {
                        eprintln!("There are no accounts.");
                        return Ok(ExitCode::FAILURE);
                    }

                    let sel_id = accounts.get_selected_account().map(|(id, _)| id);
                    let mut first = true;
                    for (id, account) in iter { // TODO: sort
                        if !first {
                            println!();
                        }

                        first = false;

                        display_account(account, sel_id.is_some_and(|s| s == id), false);
                    }
                },
                AccountCommand::Info => {
                    let Some((_, account)) = accounts.get_selected_account() else {
                        eprintln!("No account selected.");
                        return Ok(ExitCode::FAILURE);
                    };

                    display_account(account, false, true);
                },
                AccountCommand::Refresh => {
                    if cli.offline {
                        eprintln!("This command cannot be used while offline.");
                        return Ok(ExitCode::FAILURE);
                    }

                    let Some(account) = accounts.get_selected_account_mut() else {
                        eprintln!("No account selected.");
                        return Ok(ExitCode::FAILURE);
                    };

                    let client = MsaAccount::create_client();

                    match account {
                        Account::MSA(msa_acct) => {
                            msa_acct.log_in_silent(&client).await?;
                            println!("Successfully refreshed account: {}", account);
                        },
                        _ => {
                            eprintln!("Cannot refresh non-MSA account.");
                            return Ok(ExitCode::FAILURE);
                        }
                    }

                    accounts.save(&accounts_path).await?;
                }
            }
        }
        RootCommand::Launch(args) => {
            let Some(selection) = settings.selected_instance else {
                eprintln!("No instance selected.");
                return Ok(ExitCode::FAILURE);
            };
            
            let inst = settings.instances.get(&selection).expect("settings inconsistency");
            settings.save().await?;

            let accounts_path = home.join(ACCOUNT_DB_PATH);
            let mut accounts = AccountStorage::load(&accounts_path).await?;

            if !cli.offline {
                let Some(account) = accounts.get_selected_account_mut() else {
                    eprintln!("No account selected.");
                    return Ok(ExitCode::FAILURE);
                };

                if let Account::MSA(msa_acct) = account {
                    let client = MsaAccount::create_client();

                    println!("Looking up account information...");
                    match msa_acct.log_in_silent(&client).await {
                        Ok(_) => (),
                        Err(e) if e.kind() == AuthErrorKind::InteractionRequired => {
                            eprintln!("This account requires interactive authentication: {}", account);
                            eprintln!("Details: {e}");
                            return Ok(ExitCode::FAILURE);
                        },
                        Err(e) => {
                            eprintln!("Error refreshing account: {e}");
                            return Ok(ExitCode::FAILURE);
                        }
                    }
                }

                accounts.save(&accounts_path).await?;
            }

            let Some((_, account)) = accounts.get_selected_account() else {
                eprintln!("No account selected.");
                return Ok(ExitCode::FAILURE);
            };

            println!("Preparing the game files...");
            let launcher = Launcher::new(&home, !cli.offline).await?;

            let launch = launcher.prepare_launch(inst, Settings::get_instance_path(selection), settings.client_id, account, args.demo).await.map_err(|e| {
                error!("error launching: {e}");
                e
            })?;

            dbg!(&launch);
            info!("ok!");

            println!("Launching the game!");

            ozone::launcher::run_the_game(&launch)?;
        }
    }

    Ok(ExitCode::SUCCESS)
}

#[tokio::main]
async fn main() -> ExitCode {
    // use Warn as the default level to minimize noise on the command line
    simple_logger::SimpleLogger::new().env().init().unwrap();

    let arg = Cli::parse();

    main_inner(arg).await.unwrap_or_else(|e| {
        error!("Launcher initialization error:");
        error!("{e}");

        ExitCode::FAILURE
    })
}