Skip to main content

steam_client/
persistence.rs

1use std::{collections::HashMap, fs, path::PathBuf};
2
3use serde::{Deserialize, Serialize};
4
5use crate::LogOnDetails;
6
7#[derive(Serialize, Deserialize, Debug, Clone)]
8struct SavedSession {
9    account_name: String,
10    refresh_token: String,
11    steam_id: u64,
12}
13
14pub struct TokenStore {
15    path: PathBuf,
16}
17
18impl TokenStore {
19    pub fn new(filename: &str) -> Self {
20        Self { path: PathBuf::from(filename) }
21    }
22
23    /// Load all sessions from disk
24    fn load_all(&self) -> HashMap<String, SavedSession> {
25        if !self.path.exists() {
26            return HashMap::new();
27        }
28        let data = match fs::read_to_string(&self.path) {
29            Ok(d) => d,
30            Err(_) => return HashMap::new(),
31        };
32        serde_json::from_str(&data).unwrap_or_default()
33    }
34
35    /// Attempt to load a session for a specific user.
36    /// If no user specified, returns the first one found (single-user mode).
37    pub fn load(&self, account_name: Option<&str>) -> Option<LogOnDetails> {
38        let sessions = self.load_all();
39
40        let session = if let Some(name) = account_name {
41            sessions.get(name)?
42        } else {
43            // "Default" behavior: just grab the first one
44            sessions.values().next()?
45        };
46
47        Some(LogOnDetails {
48            account_name: Some(session.account_name.clone()),
49            refresh_token: Some(session.refresh_token.clone()),
50            // steam_id: Some(session.steam_id), // Useful for pre-filling
51            ..Default::default()
52        })
53    }
54
55    /// Save a token (updates existing entry or adds new one)
56    pub fn save(&self, account_name: String, token: String, steam_id: u64) -> std::io::Result<()> {
57        let mut sessions = self.load_all();
58
59        sessions.insert(account_name.clone(), SavedSession { account_name: account_name.clone(), refresh_token: token, steam_id });
60
61        let data = serde_json::to_string_pretty(&sessions)?;
62        fs::write(&self.path, data)
63    }
64}