feat(auth): add Microsoft and offline account system
This commit is contained in:
1 parent
011e0ef6bf
commit
5189eace8a
7 files changed
+1165
-11
No files matched your search
Generated
+267
-1
@@ -1142,8 +1142,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"wasi",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1173,6 +1175,18 @@ dependencies = [
|
||||
"wasip3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getset"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9cf0fc11e47561d47397154977bc219f4cf809b2974facc3ccb3b89e2436f912"
|
||||
dependencies = [
|
||||
"proc-macro-error2",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gimli"
|
||||
version = "0.28.1"
|
||||
@@ -1328,6 +1342,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower-service",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1699,6 +1714,37 @@ dependencies = [
|
||||
"thiserror 2.0.12",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyring"
|
||||
version = "3.6.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
|
||||
dependencies = [
|
||||
"log",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kinded"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce4bdbb2f423660b19f0e9f7115182214732d8dd5f840cd0a3aee3e22562f34c"
|
||||
dependencies = [
|
||||
"kinded_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kinded_macros"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a13b4ddc5dcb32f45dac3d6f606da2a52fdb9964a18427e63cd5ef6c0d13288d"
|
||||
dependencies = [
|
||||
"convert_case 0.6.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lab"
|
||||
version = "0.11.0"
|
||||
@@ -1797,6 +1843,12 @@ dependencies = [
|
||||
"hashbrown 0.16.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lru-slab"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-rs"
|
||||
version = "0.3.0"
|
||||
@@ -1849,7 +1901,10 @@ dependencies = [
|
||||
"crossterm",
|
||||
"dirs-next",
|
||||
"image",
|
||||
"keyring",
|
||||
"log",
|
||||
"minecraft-msa-auth",
|
||||
"oauth2",
|
||||
"once_cell",
|
||||
"ratatui",
|
||||
"ratatui-image",
|
||||
@@ -1905,6 +1960,20 @@ version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "minecraft-msa-auth"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7228a4ec965497200ec3a322214ecbb1c81a09935088c4b6d63eed44fc5dfc44"
|
||||
dependencies = [
|
||||
"getset",
|
||||
"nutype",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
@@ -2038,6 +2107,49 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nutype"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "362399c4581483ed2813c9b05dd6bcd903c60e61005c4b838c65ae755be69dd6"
|
||||
dependencies = [
|
||||
"nutype_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nutype_macros"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0625bcc0c714bdf12a451c4f6510b949abb095d98cc3cc8fe3812a8100ca6592"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"kinded",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
"urlencoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "oauth2"
|
||||
version = "5.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"getrandom 0.2.16",
|
||||
"http",
|
||||
"rand 0.8.5",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_path_to_error",
|
||||
"sha2",
|
||||
"thiserror 1.0.69",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "object"
|
||||
version = "0.32.2"
|
||||
@@ -2383,6 +2495,28 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-error-attr2"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-error2"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"
|
||||
dependencies = [
|
||||
"proc-macro-error-attr2",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.95"
|
||||
@@ -2418,6 +2552,61 @@ dependencies = [
|
||||
"wide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"cfg_aliases",
|
||||
"pin-project-lite",
|
||||
"quinn-proto",
|
||||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2",
|
||||
"thiserror 2.0.12",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn-proto"
|
||||
version = "0.11.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.3.4",
|
||||
"lru-slab",
|
||||
"rand 0.9.2",
|
||||
"ring",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"slab",
|
||||
"thiserror 2.0.12",
|
||||
"tinyvec",
|
||||
"tracing",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn-udp"
|
||||
version = "0.5.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
|
||||
dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.40"
|
||||
@@ -2452,7 +2641,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha",
|
||||
"rand_chacha 0.3.1",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
@@ -2462,6 +2651,7 @@ version = "0.9.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
|
||||
dependencies = [
|
||||
"rand_chacha 0.9.0",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
@@ -2475,6 +2665,16 @@ dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.4"
|
||||
@@ -2489,6 +2689,9 @@ name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_xoshiro"
|
||||
@@ -2741,6 +2944,8 @@ dependencies = [
|
||||
"native-tls",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"quinn",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2748,6 +2953,7 @@ dependencies = [
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-http",
|
||||
@@ -2757,6 +2963,7 @@ dependencies = [
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-streams",
|
||||
"web-sys",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2801,6 +3008,12 @@ version = "0.1.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f"
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
@@ -2843,6 +3056,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
@@ -2855,6 +3069,7 @@ version = "1.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
|
||||
dependencies = [
|
||||
"web-time",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
@@ -2966,6 +3181,16 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_path_to_error"
|
||||
version = "0.1.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59fab13f937fa393d08645bf3a84bdfe86e296747b506ada67bb15f10f218b2a"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "0.6.8"
|
||||
@@ -3404,6 +3629,21 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
|
||||
dependencies = [
|
||||
"tinyvec_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec_macros"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.50.0"
|
||||
@@ -3767,8 +4007,15 @@ dependencies = [
|
||||
"idna",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "urlencoding"
|
||||
version = "2.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.0.4"
|
||||
@@ -3971,6 +4218,25 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-time"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wezterm-bidi"
|
||||
version = "0.2.3"
|
||||
|
||||
@@ -34,6 +34,9 @@ tui-widget-list = "0.15"
|
||||
ratatui-image = { version = "10.0.6", default-features = false, features = ["crossterm"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
zip = "2"
|
||||
minecraft-msa-auth = "0.4.0"
|
||||
keyring = "3.6.3"
|
||||
oauth2 = "5.0.0"
|
||||
|
||||
|
||||
[profile.release]
|
||||
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use minecraft_msa_auth::MinecraftAuthorizationFlow;
|
||||
use oauth2::basic::BasicClient;
|
||||
use oauth2::{
|
||||
AuthUrl, ClientId, DeviceAuthorizationUrl, Scope, StandardDeviceAuthorizationResponse,
|
||||
TokenResponse, TokenUrl,
|
||||
};
|
||||
use once_cell::sync::Lazy;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const CLIENT_ID: &str = "cc1b2d89-8d8b-439f-94e6-4a7fc484f672";
|
||||
const DEVICE_CODE_URL: &str =
|
||||
"https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode";
|
||||
const MSA_AUTHORIZE_URL: &str =
|
||||
"https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize";
|
||||
const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
|
||||
const REFRESH_URL: &str = "https://login.live.com/oauth20_token.srf";
|
||||
const MC_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile";
|
||||
const KEYRING_SERVICE: &str = "mcl-launcher";
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Account {
|
||||
pub uuid: String,
|
||||
pub username: String,
|
||||
pub account_type: AccountType,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub enum AccountType {
|
||||
Microsoft,
|
||||
Offline,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DeviceCodeInfo {
|
||||
pub user_code: String,
|
||||
pub verification_uri: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AuthResult {
|
||||
Success(Account),
|
||||
Error(String),
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RefreshTokenResponse {
|
||||
access_token: String,
|
||||
refresh_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct McProfile {
|
||||
id: String,
|
||||
name: String,
|
||||
}
|
||||
|
||||
// ── Account Store ──────────────────────────────────────────────
|
||||
|
||||
pub struct AccountStore {
|
||||
pub accounts: Vec<Account>,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl AccountStore {
|
||||
pub fn load() -> Self {
|
||||
let path = account_store_path();
|
||||
let accounts = match std::fs::read_to_string(&path) {
|
||||
Ok(content) => serde_json::from_str(&content).unwrap_or_default(),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
Self { accounts, path }
|
||||
}
|
||||
|
||||
pub fn save(&self) {
|
||||
if let Some(parent) = self.path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
if let Ok(json) = serde_json::to_string_pretty(&self.accounts) {
|
||||
let _ = std::fs::write(&self.path, json);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn active_account(&self) -> Option<&Account> {
|
||||
self.accounts.iter().find(|a| a.active)
|
||||
}
|
||||
|
||||
pub fn set_active(&mut self, index: usize) {
|
||||
for (i, acc) in self.accounts.iter_mut().enumerate() {
|
||||
acc.active = i == index;
|
||||
}
|
||||
self.save();
|
||||
}
|
||||
|
||||
pub fn add(&mut self, account: Account) {
|
||||
let is_first = self.accounts.is_empty();
|
||||
let uuid = account.uuid.clone();
|
||||
self.accounts.retain(|a| a.uuid != uuid);
|
||||
let mut account = account;
|
||||
if is_first {
|
||||
account.active = true;
|
||||
}
|
||||
self.accounts.push(account);
|
||||
self.save();
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, index: usize) {
|
||||
if index >= self.accounts.len() {
|
||||
return;
|
||||
}
|
||||
let account = self.accounts.remove(index);
|
||||
if account.account_type == AccountType::Microsoft {
|
||||
let _ = delete_refresh_token(&account.uuid);
|
||||
}
|
||||
if account.active && !self.accounts.is_empty() {
|
||||
self.accounts[0].active = true;
|
||||
}
|
||||
self.save();
|
||||
}
|
||||
}
|
||||
|
||||
fn account_store_path() -> PathBuf {
|
||||
dirs_next::config_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join("mcl")
|
||||
.join("accounts.json")
|
||||
}
|
||||
|
||||
// ── Keyring ────────────────────────────────────────────────────
|
||||
|
||||
fn store_refresh_token(uuid: &str, token: &str) -> Result<(), String> {
|
||||
let entry = keyring::Entry::new(KEYRING_SERVICE, &format!("refresh:{uuid}"))
|
||||
.map_err(|e| e.to_string())?;
|
||||
entry.set_password(token).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn get_refresh_token(uuid: &str) -> Result<String, String> {
|
||||
let entry = keyring::Entry::new(KEYRING_SERVICE, &format!("refresh:{uuid}"))
|
||||
.map_err(|e| e.to_string())?;
|
||||
entry.get_password().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn delete_refresh_token(uuid: &str) -> Result<(), String> {
|
||||
let entry = keyring::Entry::new(KEYRING_SERVICE, &format!("refresh:{uuid}"))
|
||||
.map_err(|e| e.to_string())?;
|
||||
entry.delete_credential().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ── Offline ────────────────────────────────────────────────────
|
||||
|
||||
pub fn offline_uuid(username: &str) -> String {
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = DefaultHasher::new();
|
||||
format!("OfflinePlayer:{username}").hash(&mut hasher);
|
||||
let h = hasher.finish();
|
||||
format!(
|
||||
"{:08x}-{:04x}-3{:03x}-{:04x}-{:012x}",
|
||||
(h >> 32) as u32,
|
||||
(h >> 16) as u16 & 0xFFFF,
|
||||
(h >> 4) as u16 & 0x0FFF,
|
||||
(h as u16 & 0x3FFF) | 0x8000,
|
||||
h & 0xFFFFFFFFFFFF,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn create_offline_account(username: &str) -> Account {
|
||||
Account {
|
||||
uuid: offline_uuid(username),
|
||||
username: username.to_string(),
|
||||
account_type: AccountType::Offline,
|
||||
active: false,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Microsoft Auth (oauth2 + minecraft-msa-auth) ───────────────
|
||||
|
||||
pub static DEVICE_CODE_DISPLAY: Lazy<Arc<Mutex<Option<DeviceCodeInfo>>>> =
|
||||
Lazy::new(|| Arc::new(Mutex::new(None)));
|
||||
|
||||
async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
|
||||
let oauth_client = BasicClient::new(ClientId::new(CLIENT_ID.to_string()))
|
||||
.set_auth_uri(AuthUrl::new(MSA_AUTHORIZE_URL.to_string()).map_err(|e| e.to_string())?)
|
||||
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_string()).map_err(|e| e.to_string())?)
|
||||
.set_device_authorization_url(
|
||||
DeviceAuthorizationUrl::new(DEVICE_CODE_URL.to_string()).map_err(|e| e.to_string())?,
|
||||
);
|
||||
|
||||
let http_client = reqwest::Client::new();
|
||||
|
||||
let details: StandardDeviceAuthorizationResponse = oauth_client
|
||||
.exchange_device_code()
|
||||
.add_scope(Scope::new("XboxLive.signin offline_access".to_string()))
|
||||
.request_async(&http_client)
|
||||
.await
|
||||
.map_err(|e| format!("Device code request failed: {e}"))?;
|
||||
|
||||
if let Ok(mut slot) = DEVICE_CODE_DISPLAY.lock() {
|
||||
*slot = Some(DeviceCodeInfo {
|
||||
user_code: details.user_code().secret().to_string(),
|
||||
verification_uri: details.verification_uri().to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let token = oauth_client
|
||||
.exchange_device_access_token(&details)
|
||||
.request_async(&http_client, tokio::time::sleep, None)
|
||||
.await
|
||||
.map_err(|e| format!("Authentication failed: {e}"))?;
|
||||
|
||||
let ms_access_token = token.access_token().secret().to_string();
|
||||
let ms_refresh_token = token.refresh_token().map(|r| r.secret().to_string());
|
||||
|
||||
Ok((ms_access_token, ms_refresh_token))
|
||||
}
|
||||
|
||||
pub fn start_microsoft_auth() -> Arc<Mutex<Option<AuthResult>>> {
|
||||
let result: Arc<Mutex<Option<AuthResult>>> = Arc::new(Mutex::new(None));
|
||||
let result_clone = result.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let outcome = run_full_auth_flow().await;
|
||||
if let Ok(mut slot) = result_clone.lock() {
|
||||
*slot = Some(outcome);
|
||||
}
|
||||
});
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
async fn run_full_auth_flow() -> AuthResult {
|
||||
let (ms_access_token, ms_refresh_token) = match run_full_oauth_flow().await {
|
||||
Ok(pair) => pair,
|
||||
Err(e) => return AuthResult::Error(e),
|
||||
};
|
||||
|
||||
exchange_and_build_account(&ms_access_token, ms_refresh_token.as_deref()).await
|
||||
}
|
||||
|
||||
async fn exchange_and_build_account(
|
||||
ms_access_token: &str,
|
||||
ms_refresh_token: Option<&str>,
|
||||
) -> AuthResult {
|
||||
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
|
||||
let mc_token = match mc_flow.exchange_microsoft_token(ms_access_token).await {
|
||||
Ok(t) => t,
|
||||
Err(e) => return AuthResult::Error(format!("Minecraft auth failed: {e}")),
|
||||
};
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let profile_resp = match client
|
||||
.get(MC_PROFILE_URL)
|
||||
.header(
|
||||
"Authorization",
|
||||
format!("Bearer {}", mc_token.access_token().as_ref()),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(r) => r,
|
||||
Err(e) => return AuthResult::Error(format!("Profile fetch failed: {e}")),
|
||||
};
|
||||
|
||||
if !profile_resp.status().is_success() {
|
||||
return AuthResult::Error("Account does not own Minecraft".to_string());
|
||||
}
|
||||
|
||||
let profile: McProfile = match profile_resp.json().await {
|
||||
Ok(p) => p,
|
||||
Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")),
|
||||
};
|
||||
|
||||
let uuid = if profile.id.len() == 32 {
|
||||
format!(
|
||||
"{}-{}-{}-{}-{}",
|
||||
&profile.id[..8],
|
||||
&profile.id[8..12],
|
||||
&profile.id[12..16],
|
||||
&profile.id[16..20],
|
||||
&profile.id[20..32],
|
||||
)
|
||||
} else {
|
||||
profile.id.clone()
|
||||
};
|
||||
|
||||
if let Some(refresh) = ms_refresh_token {
|
||||
let _ = store_refresh_token(&uuid, refresh);
|
||||
}
|
||||
|
||||
AuthResult::Success(Account {
|
||||
uuid,
|
||||
username: profile.name,
|
||||
account_type: AccountType::Microsoft,
|
||||
active: false,
|
||||
})
|
||||
}
|
||||
|
||||
// ── Token Refresh ──────────────────────────────────────────────
|
||||
|
||||
pub async fn refresh_and_get_token(account: &Account) -> Result<String, String> {
|
||||
match account.account_type {
|
||||
AccountType::Offline => Ok("0".to_string()),
|
||||
AccountType::Microsoft => {
|
||||
let refresh = get_refresh_token(&account.uuid)?;
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let resp = client
|
||||
.post(REFRESH_URL)
|
||||
.form(&[
|
||||
("client_id", CLIENT_ID),
|
||||
("refresh_token", refresh.as_str()),
|
||||
("grant_type", "refresh_token"),
|
||||
(
|
||||
"redirect_uri",
|
||||
"https://login.microsoftonline.com/common/oauth2/nativeclient",
|
||||
),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let token: RefreshTokenResponse = resp.json().await.map_err(|e| e.to_string())?;
|
||||
|
||||
if let Some(new_refresh) = &token.refresh_token {
|
||||
let _ = store_refresh_token(&account.uuid, new_refresh);
|
||||
}
|
||||
|
||||
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
|
||||
let mc_token = mc_flow
|
||||
.exchange_microsoft_token(&token.access_token)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
Ok(mc_token.access_token().as_ref().to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
-4
@@ -233,9 +233,46 @@ pub async fn launch(
|
||||
];
|
||||
jvm.extend(config.jvm_args.clone());
|
||||
|
||||
let account_store = crate::auth::AccountStore::load();
|
||||
let (mc_username, mc_uuid, mc_token, mc_user_type) =
|
||||
match account_store.active_account() {
|
||||
Some(acc) => {
|
||||
let token = match acc.account_type {
|
||||
crate::auth::AccountType::Microsoft => {
|
||||
match tokio::runtime::Handle::current()
|
||||
.block_on(crate::auth::refresh_and_get_token(acc))
|
||||
{
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
tracing::error!("Token refresh failed: {e}");
|
||||
"0".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::auth::AccountType::Offline => "0".to_string(),
|
||||
};
|
||||
let user_type = match acc.account_type {
|
||||
crate::auth::AccountType::Microsoft => "msa",
|
||||
crate::auth::AccountType::Offline => "legacy",
|
||||
};
|
||||
(
|
||||
acc.username.clone(),
|
||||
acc.uuid.clone(),
|
||||
token,
|
||||
user_type.to_string(),
|
||||
)
|
||||
}
|
||||
None => (
|
||||
"Player".to_string(),
|
||||
"00000000-0000-0000-0000-000000000000".to_string(),
|
||||
"0".to_string(),
|
||||
"legacy".to_string(),
|
||||
),
|
||||
};
|
||||
|
||||
let game_args = vec![
|
||||
"--username".to_string(),
|
||||
"Player".to_string(),
|
||||
mc_username,
|
||||
"--version".to_string(),
|
||||
config.game_version.clone(),
|
||||
"--gameDir".to_string(),
|
||||
@@ -245,11 +282,11 @@ pub async fn launch(
|
||||
"--assetIndex".to_string(),
|
||||
meta.asset_index.id.clone(),
|
||||
"--uuid".to_string(),
|
||||
"00000000-0000-0000-0000-000000000000".to_string(),
|
||||
mc_uuid,
|
||||
"--accessToken".to_string(),
|
||||
"0".to_string(),
|
||||
mc_token,
|
||||
"--userType".to_string(),
|
||||
"legacy".to_string(),
|
||||
mc_user_type,
|
||||
];
|
||||
|
||||
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod auth;
|
||||
mod cli;
|
||||
pub mod config;
|
||||
pub mod instance;
|
||||
|
||||
+11
-1
@@ -37,6 +37,7 @@ pub struct App {
|
||||
worlds_state: widgets::content_list::ContentListState,
|
||||
screenshots_state: widgets::screenshots_grid::ScreenshotsState,
|
||||
logs_state: widgets::logs_viewer::LogsState,
|
||||
account_state: widgets::account::AccountState,
|
||||
picker: ratatui_image::picker::Picker,
|
||||
instance_manager: InstanceManager,
|
||||
log_list_state: tui_logger::TuiWidgetState,
|
||||
@@ -99,6 +100,7 @@ impl App {
|
||||
shaders_state: widgets::content_list::ContentListState::default(),
|
||||
worlds_state: widgets::content_list::ContentListState::default(),
|
||||
logs_state: widgets::logs_viewer::LogsState::default(),
|
||||
account_state: widgets::account::AccountState::default(),
|
||||
screenshots_state: {
|
||||
let mut s = widgets::screenshots_grid::ScreenshotsState::default();
|
||||
s.font_size = picker.font_size();
|
||||
@@ -132,6 +134,8 @@ impl App {
|
||||
self.worlds_state.drain_pending();
|
||||
self.logs_state.drain_pending();
|
||||
self.logs_state.try_rescan();
|
||||
self.account_state.drain_auth_result();
|
||||
widgets::account::drain_device_code(&mut self.account_state);
|
||||
self.screenshots_state.drain_pending_entries();
|
||||
self.screenshots_state.request_visible_loads();
|
||||
self.create_screenshot_protocols();
|
||||
@@ -197,7 +201,7 @@ impl App {
|
||||
])
|
||||
.split(main_chunks[2]);
|
||||
|
||||
widgets::account::render(frame, bottom_chunks[0], self.focused);
|
||||
widgets::account::render(frame, bottom_chunks[0], self.focused, &mut self.account_state);
|
||||
widgets::details::render(frame, bottom_chunks[1], self.focused);
|
||||
widgets::status::render(frame, bottom_chunks[2], self.focused, &mut self.throbber_state);
|
||||
|
||||
@@ -345,6 +349,12 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
if self.focused == FocusedArea::Account {
|
||||
if widgets::account::handle_key(&key_event, &mut self.account_state) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
match self.focused {
|
||||
FocusedArea::Popup => {
|
||||
new_instance::handle_key(&key_event, &mut self.profiles_state);
|
||||
|
||||
+502
-5
@@ -1,16 +1,218 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use ratatui::{
|
||||
layout::Rect,
|
||||
style::Style,
|
||||
widgets::{Block, BorderType, Borders, Paragraph},
|
||||
style::{Color, Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, BorderType, Borders, Paragraph, Widget},
|
||||
Frame,
|
||||
};
|
||||
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
||||
|
||||
use crate::auth::{self, AccountStore, AccountType, AuthResult, DeviceCodeInfo};
|
||||
use crate::tui::layout::FocusedArea;
|
||||
use crate::tui::theme::THEME;
|
||||
|
||||
use super::styled_title;
|
||||
|
||||
pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea) {
|
||||
#[derive(Default)]
|
||||
pub enum AddMode {
|
||||
#[default]
|
||||
None,
|
||||
ChooseType,
|
||||
OfflineNameInput(String),
|
||||
ConfirmDelete(usize),
|
||||
DeviceCodeWaiting {
|
||||
info: DeviceCodeInfo,
|
||||
pending: Arc<Mutex<Option<AuthResult>>>,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct AccountState {
|
||||
pub store: AccountStore,
|
||||
pub list_state: TuiListState,
|
||||
pub add_mode: AddMode,
|
||||
}
|
||||
|
||||
impl Default for AccountState {
|
||||
fn default() -> Self {
|
||||
let store = AccountStore::load();
|
||||
let mut list_state = TuiListState::default();
|
||||
if !store.accounts.is_empty() {
|
||||
list_state.selected = Some(0);
|
||||
}
|
||||
Self {
|
||||
store,
|
||||
list_state,
|
||||
add_mode: AddMode::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AccountState {
|
||||
pub fn drain_auth_result(&mut self) {
|
||||
if let AddMode::DeviceCodeWaiting { pending, .. } = &self.add_mode {
|
||||
let result = if let Ok(mut slot) = pending.lock() {
|
||||
slot.take()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(result) = result {
|
||||
match result {
|
||||
AuthResult::Success(account) => {
|
||||
self.store.add(account);
|
||||
self.add_mode = AddMode::None;
|
||||
if self.list_state.selected.is_none() && !self.store.accounts.is_empty() {
|
||||
self.list_state.selected = Some(0);
|
||||
}
|
||||
}
|
||||
AuthResult::Error(e) => {
|
||||
tracing::error!("Microsoft auth failed: {}", e);
|
||||
self.add_mode = AddMode::None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
|
||||
match &state.add_mode {
|
||||
AddMode::ChooseType => match key_event.code {
|
||||
KeyCode::Char('m') | KeyCode::Char('1') => {
|
||||
let pending = auth::start_microsoft_auth();
|
||||
state.add_mode = AddMode::DeviceCodeWaiting {
|
||||
info: DeviceCodeInfo {
|
||||
user_code: String::new(),
|
||||
verification_uri: String::new(),
|
||||
},
|
||||
pending,
|
||||
};
|
||||
true
|
||||
}
|
||||
KeyCode::Char('o') | KeyCode::Char('2') => {
|
||||
state.add_mode = AddMode::OfflineNameInput(String::new());
|
||||
true
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
state.add_mode = AddMode::None;
|
||||
true
|
||||
}
|
||||
_ => true,
|
||||
},
|
||||
AddMode::OfflineNameInput(name) => match key_event.code {
|
||||
KeyCode::Enter => {
|
||||
let trimmed = name.trim().to_string();
|
||||
if !trimmed.is_empty() {
|
||||
let account = auth::create_offline_account(&trimmed);
|
||||
state.store.add(account);
|
||||
if state.list_state.selected.is_none() && !state.store.accounts.is_empty() {
|
||||
state.list_state.selected = Some(0);
|
||||
}
|
||||
}
|
||||
state.add_mode = AddMode::None;
|
||||
true
|
||||
}
|
||||
KeyCode::Char(c) => {
|
||||
let mut new_name = name.clone();
|
||||
new_name.push(c);
|
||||
state.add_mode = AddMode::OfflineNameInput(new_name);
|
||||
true
|
||||
}
|
||||
KeyCode::Backspace => {
|
||||
let mut new_name = name.clone();
|
||||
new_name.pop();
|
||||
state.add_mode = AddMode::OfflineNameInput(new_name);
|
||||
true
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
state.add_mode = AddMode::None;
|
||||
true
|
||||
}
|
||||
_ => true,
|
||||
},
|
||||
AddMode::DeviceCodeWaiting { .. } => match key_event.code {
|
||||
KeyCode::Esc => {
|
||||
state.add_mode = AddMode::None;
|
||||
true
|
||||
}
|
||||
_ => true,
|
||||
},
|
||||
AddMode::ConfirmDelete(idx) => {
|
||||
let idx = *idx;
|
||||
match key_event.code {
|
||||
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
|
||||
let count = state.store.accounts.len();
|
||||
state.store.remove(idx);
|
||||
if count > 1 {
|
||||
state.list_state.selected =
|
||||
Some(idx.min(state.store.accounts.len().saturating_sub(1)));
|
||||
} else {
|
||||
state.list_state.selected = None;
|
||||
}
|
||||
state.add_mode = AddMode::None;
|
||||
true
|
||||
}
|
||||
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
|
||||
state.add_mode = AddMode::None;
|
||||
true
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
AddMode::None => {
|
||||
let count = state.store.accounts.len();
|
||||
match key_event.code {
|
||||
KeyCode::Char('a') => {
|
||||
state.add_mode = AddMode::ChooseType;
|
||||
true
|
||||
}
|
||||
KeyCode::Char('d') => {
|
||||
if let Some(idx) = state.list_state.selected {
|
||||
state.add_mode = AddMode::ConfirmDelete(idx);
|
||||
}
|
||||
true
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
if let Some(idx) = state.list_state.selected {
|
||||
state.store.set_active(idx);
|
||||
}
|
||||
true
|
||||
}
|
||||
KeyCode::Char('j') | KeyCode::Down => {
|
||||
if count > 0 {
|
||||
let cur = state.list_state.selected.unwrap_or(0);
|
||||
state.list_state.selected = Some((cur + 1).min(count - 1));
|
||||
}
|
||||
true
|
||||
}
|
||||
KeyCode::Char('k') | KeyCode::Up => {
|
||||
let cur = state.list_state.selected.unwrap_or(0);
|
||||
state.list_state.selected = Some(cur.saturating_sub(1));
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn drain_device_code(state: &mut AccountState) {
|
||||
if let AddMode::DeviceCodeWaiting { info, .. } = &mut state.add_mode {
|
||||
if info.user_code.is_empty() {
|
||||
if let Ok(mut slot) = auth::DEVICE_CODE_DISPLAY.lock() {
|
||||
if let Some(dc_info) = slot.take() {
|
||||
info.user_code = dc_info.user_code;
|
||||
info.verification_uri = dc_info.verification_uri;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut AccountState) {
|
||||
let color = if focused == FocusedArea::Account {
|
||||
THEME.colors.border_focused
|
||||
} else {
|
||||
@@ -23,6 +225,301 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea) {
|
||||
.border_type(BorderType::Rounded)
|
||||
.border_style(Style::default().fg(color));
|
||||
|
||||
let widget = Paragraph::new("TEST CONTENT").block(block);
|
||||
frame.render_widget(widget, area);
|
||||
let inner = block.inner(area);
|
||||
frame.render_widget(block, area);
|
||||
|
||||
if state.store.accounts.is_empty() {
|
||||
frame.render_widget(
|
||||
Paragraph::new("No accounts. Press 'a' to add.")
|
||||
.style(Style::default().fg(THEME.colors.text_idle)),
|
||||
inner,
|
||||
);
|
||||
} else {
|
||||
let active = state.store.active_account().map(|a| a.uuid.clone());
|
||||
render_account_list(frame, inner, state, focused, active.as_deref());
|
||||
}
|
||||
|
||||
match &state.add_mode {
|
||||
AddMode::ChooseType => render_choose_popup(frame),
|
||||
AddMode::OfflineNameInput(name) => render_offline_popup(frame, name),
|
||||
AddMode::ConfirmDelete(idx) => render_confirm_delete(frame, state, *idx),
|
||||
AddMode::DeviceCodeWaiting { info, .. } => render_device_code_popup(frame, info),
|
||||
AddMode::None => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_account_list(
|
||||
frame: &mut Frame,
|
||||
area: Rect,
|
||||
state: &mut AccountState,
|
||||
focused: FocusedArea,
|
||||
active_uuid: Option<&str>,
|
||||
) {
|
||||
let is_focused = focused == FocusedArea::Account;
|
||||
let accounts: Vec<(String, AccountType, bool)> = state
|
||||
.store
|
||||
.accounts
|
||||
.iter()
|
||||
.map(|a| {
|
||||
(
|
||||
a.username.clone(),
|
||||
a.account_type.clone(),
|
||||
active_uuid == Some(&a.uuid),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let count = accounts.len();
|
||||
|
||||
let builder = ListBuilder::new(move |context| {
|
||||
let (username, acc_type, is_active) = &accounts[context.index];
|
||||
let show_selected = is_focused && context.is_selected;
|
||||
|
||||
let stripe_bg = if context.index % 2 == 0 {
|
||||
Color::Reset
|
||||
} else {
|
||||
THEME.colors.row_alternate_bg
|
||||
};
|
||||
|
||||
let bg = if show_selected {
|
||||
THEME.colors.row_background
|
||||
} else {
|
||||
stripe_bg
|
||||
};
|
||||
|
||||
let active_marker = if *is_active { "\u{25b8} " } else { " " };
|
||||
|
||||
let style = if show_selected {
|
||||
Style::default()
|
||||
.fg(THEME.colors.row_highlight)
|
||||
.add_modifier(Modifier::BOLD)
|
||||
} else if *is_active {
|
||||
Style::default()
|
||||
.fg(THEME.colors.foreground)
|
||||
.add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
Style::default().fg(THEME.colors.foreground)
|
||||
};
|
||||
|
||||
let mut spans = vec![
|
||||
Span::styled(active_marker, Style::default().fg(THEME.colors.accent)),
|
||||
Span::styled(username.clone(), style),
|
||||
];
|
||||
|
||||
if *acc_type == AccountType::Offline {
|
||||
let offline_style = if show_selected {
|
||||
Style::default().fg(THEME.colors.row_highlight)
|
||||
} else {
|
||||
Style::default().fg(THEME.colors.text_idle)
|
||||
};
|
||||
spans.push(Span::styled(" (Offline)", offline_style));
|
||||
}
|
||||
|
||||
let item = ratatui::text::Text::from(Line::from(spans)).style(Style::default().bg(bg));
|
||||
(item, 1)
|
||||
});
|
||||
|
||||
let list = ListView::new(builder, count);
|
||||
frame.render_stateful_widget(list, area, &mut state.list_state);
|
||||
}
|
||||
|
||||
fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect {
|
||||
let area = frame.area();
|
||||
let x = area.x + (area.width.saturating_sub(width)) / 2;
|
||||
let y = area.y + (area.height.saturating_sub(height)) / 2;
|
||||
Rect {
|
||||
x,
|
||||
y,
|
||||
width: width.min(area.width),
|
||||
height: height.min(area.height),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_choose_popup(frame: &mut Frame) {
|
||||
use super::popups::base::PopupFrame;
|
||||
let area = popup_area(frame, 40, 7);
|
||||
|
||||
PopupFrame {
|
||||
title: Line::from(" Add Account ").centered(),
|
||||
border_color: THEME.colors.border_focused,
|
||||
bg: None,
|
||||
keybinds: Some(Line::from(Span::styled(
|
||||
" Esc: cancel ",
|
||||
Style::default().fg(THEME.colors.text_idle),
|
||||
))),
|
||||
search_line: None,
|
||||
content: Box::new(|inner, buf| {
|
||||
let text = vec![
|
||||
Line::from(""),
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
" [m] ",
|
||||
Style::default()
|
||||
.fg(THEME.colors.accent)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Span::styled(
|
||||
"Microsoft Account",
|
||||
Style::default().fg(THEME.colors.foreground),
|
||||
),
|
||||
]),
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
" [o] ",
|
||||
Style::default()
|
||||
.fg(THEME.colors.accent)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Span::styled(
|
||||
"Offline Account",
|
||||
Style::default().fg(THEME.colors.foreground),
|
||||
),
|
||||
]),
|
||||
];
|
||||
Paragraph::new(text).render(inner, buf);
|
||||
}),
|
||||
}
|
||||
.render(area, frame.buffer_mut());
|
||||
}
|
||||
|
||||
fn render_offline_popup(frame: &mut Frame, name: &str) {
|
||||
use super::popups::{base::PopupFrame, keybind_line};
|
||||
let area = popup_area(frame, 40, 5);
|
||||
let name = name.to_string();
|
||||
|
||||
PopupFrame {
|
||||
title: Line::from(Span::styled(
|
||||
" Offline Account ",
|
||||
Style::default()
|
||||
.fg(THEME.colors.border_focused)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
))
|
||||
.centered(),
|
||||
border_color: THEME.colors.border_focused,
|
||||
bg: Some(THEME.colors.popup_bg),
|
||||
keybinds: Some(keybind_line(&[("Enter", " confirm"), ("Esc", " cancel")])),
|
||||
search_line: None,
|
||||
content: Box::new(move |inner, buf| {
|
||||
let line = if name.is_empty() {
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
"Username...",
|
||||
Style::default().fg(THEME.colors.border_unfocused),
|
||||
),
|
||||
Span::styled(
|
||||
"\u{2588}",
|
||||
Style::default()
|
||||
.fg(THEME.colors.border_focused)
|
||||
.add_modifier(Modifier::SLOW_BLINK),
|
||||
),
|
||||
])
|
||||
} else {
|
||||
Line::from(vec![
|
||||
Span::styled(name.as_str(), Style::default().fg(THEME.colors.foreground)),
|
||||
Span::styled(
|
||||
"\u{2588}",
|
||||
Style::default()
|
||||
.fg(THEME.colors.border_focused)
|
||||
.add_modifier(Modifier::SLOW_BLINK),
|
||||
),
|
||||
])
|
||||
};
|
||||
Paragraph::new(line).render(inner, buf);
|
||||
}),
|
||||
}
|
||||
.render(area, frame.buffer_mut());
|
||||
}
|
||||
|
||||
fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
|
||||
use super::popups::{base::PopupFrame, keybind_line};
|
||||
let username = state
|
||||
.store
|
||||
.accounts
|
||||
.get(idx)
|
||||
.map(|a| a.username.as_str())
|
||||
.unwrap_or("?");
|
||||
|
||||
let title = Line::from(Span::styled(
|
||||
format!(" Delete '{}' ", username),
|
||||
Style::default()
|
||||
.fg(THEME.colors.border_focused)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
));
|
||||
|
||||
let body = "This will permanently remove this account";
|
||||
let popup_w = (username.len() + 14).max(body.len() + 2).min(48) as u16 + 2;
|
||||
let area = popup_area(frame, popup_w, 3);
|
||||
|
||||
PopupFrame {
|
||||
title,
|
||||
border_color: THEME.colors.border_focused,
|
||||
bg: Some(THEME.colors.row_alternate_bg),
|
||||
keybinds: Some(keybind_line(&[("Enter", " confirm")])),
|
||||
search_line: None,
|
||||
content: Box::new(|inner, buf| {
|
||||
Paragraph::new("This will permanently remove this account")
|
||||
.style(Style::default().fg(THEME.colors.foreground))
|
||||
.render(inner, buf);
|
||||
}),
|
||||
}
|
||||
.render(area, frame.buffer_mut());
|
||||
}
|
||||
|
||||
fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
|
||||
use super::popups::{base::PopupFrame, keybind_line};
|
||||
let area = popup_area(frame, 50, 8);
|
||||
let uri = info.verification_uri.clone();
|
||||
let code = info.user_code.clone();
|
||||
|
||||
PopupFrame {
|
||||
title: Line::from(Span::styled(
|
||||
" Microsoft Login ",
|
||||
Style::default()
|
||||
.fg(THEME.colors.border_focused)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
))
|
||||
.centered(),
|
||||
border_color: THEME.colors.border_focused,
|
||||
bg: Some(THEME.colors.popup_bg),
|
||||
keybinds: Some(keybind_line(&[("Esc", " cancel")])),
|
||||
search_line: None,
|
||||
content: Box::new(move |inner, buf| {
|
||||
let text = if code.is_empty() {
|
||||
vec![Line::from(Span::styled(
|
||||
"Connecting to Microsoft...",
|
||||
Style::default().fg(THEME.colors.text_idle),
|
||||
))]
|
||||
} else {
|
||||
vec![
|
||||
Line::from(Span::styled(
|
||||
"Open this URL in your browser:",
|
||||
Style::default().fg(THEME.colors.text_idle),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
uri.as_str(),
|
||||
Style::default()
|
||||
.fg(THEME.colors.accent)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
)),
|
||||
Line::from(""),
|
||||
Line::from(vec![
|
||||
Span::styled("Enter code: ", Style::default().fg(THEME.colors.text_idle)),
|
||||
Span::styled(
|
||||
code.as_str(),
|
||||
Style::default()
|
||||
.fg(THEME.colors.success)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
]),
|
||||
Line::from(""),
|
||||
Line::from(Span::styled(
|
||||
"Waiting for authentication...",
|
||||
Style::default().fg(THEME.colors.text_idle),
|
||||
)),
|
||||
]
|
||||
};
|
||||
Paragraph::new(text).render(inner, buf);
|
||||
}),
|
||||
}
|
||||
.render(area, frame.buffer_mut());
|
||||
}
|
||||
Reference in new issue
Block a user