1use std::path::Path;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8use tokio::fs::File;
9use tokio::io::{AsyncReadExt, AsyncWriteExt};
10use tracing::{debug, trace};
11
12#[derive(Debug, Error)]
13pub enum CacheError {
14 #[error("Failed to read cache file: {0}")]
15 Read(std::io::Error),
16 #[error("Failed to write cache file: {0}")]
17 Write(std::io::Error),
18 #[error("Failed to create cache file directory: {0}")]
19 MkDir(std::io::Error),
20 #[error("Failed to parse cache file: {0}")]
21 Parse(serde_json::Error),
22}
23
24#[derive(Deserialize, Serialize, Debug)]
25pub struct CachedAccount {
26 pub email: String,
27 pub msa: ExpiringValue<crate::auth::AccessTokenResponse>,
29 pub xbl: ExpiringValue<crate::auth::XboxLiveAuth>,
31 pub mca: ExpiringValue<crate::auth::MinecraftAuthResponse>,
33 pub profile: crate::auth::ProfileResponse,
35}
36
37#[derive(Deserialize, Serialize, Debug)]
38pub struct ExpiringValue<T> {
39 pub expires_at: u64,
41 pub data: T,
42}
43
44impl<T> ExpiringValue<T> {
45 pub fn is_expired(&self) -> bool {
46 self.expires_at
47 < SystemTime::now()
48 .duration_since(UNIX_EPOCH)
49 .unwrap()
50 .as_secs()
51 }
52
53 pub fn get(&self) -> Option<&T> {
55 if self.is_expired() {
56 None
57 } else {
58 Some(&self.data)
59 }
60 }
61}
62
63impl<T: Clone> Clone for ExpiringValue<T> {
64 fn clone(&self) -> Self {
65 Self {
66 expires_at: self.expires_at,
67 data: self.data.clone(),
68 }
69 }
70}
71
72async fn get_entire_cache(cache_file: &Path) -> Result<Vec<CachedAccount>, CacheError> {
73 let mut cache: Vec<CachedAccount> = Vec::new();
74 if cache_file.exists() {
75 let mut cache_file = File::open(cache_file).await.map_err(CacheError::Read)?;
76 let mut contents = String::new();
78 cache_file
79 .read_to_string(&mut contents)
80 .await
81 .map_err(CacheError::Read)?;
82 cache = serde_json::from_str(&contents).map_err(CacheError::Parse)?;
83 }
84 Ok(cache)
85}
86async fn set_entire_cache(cache_file: &Path, cache: Vec<CachedAccount>) -> Result<(), CacheError> {
87 trace!("saving cache: {:?}", cache);
88
89 if !cache_file.exists() {
90 let cache_file_parent = cache_file
91 .parent()
92 .expect("Cache file is root directory and also doesn't exist.");
93 debug!(
94 "Making cache file parent directory at {}",
95 cache_file_parent.to_string_lossy()
96 );
97 std::fs::create_dir_all(cache_file_parent).map_err(CacheError::MkDir)?;
98 }
99 let mut cache_file = File::create(cache_file).await.map_err(CacheError::Write)?;
100 let cache = serde_json::to_string_pretty(&cache).map_err(CacheError::Parse)?;
101 cache_file
102 .write_all(cache.as_bytes())
103 .await
104 .map_err(CacheError::Write)?;
105
106 Ok(())
107}
108
109pub async fn get_account_in_cache(cache_file: &Path, email: &str) -> Option<CachedAccount> {
115 let cache = get_entire_cache(cache_file).await.unwrap_or_default();
116 cache.into_iter().find(|account| account.email == email)
117}
118
119pub async fn set_account_in_cache(
120 cache_file: &Path,
121 email: &str,
122 account: CachedAccount,
123) -> Result<(), CacheError> {
124 let mut cache = get_entire_cache(cache_file).await.unwrap_or_default();
125 cache.retain(|account| account.email != email);
126 cache.push(account);
127 set_entire_cache(cache_file, cache).await
128}