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
+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