1use std::path::PathBuf;
2
3use serde::{Deserialize, Serialize};
4use uuid::Uuid;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct SessionConfig {
8 pub api_base: String,
9 pub session_token: String,
10 #[serde(default)]
12 pub last_character_id: Option<Uuid>,
13}
14
15impl SessionConfig {
16 pub fn path() -> anyhow::Result<PathBuf> {
17 let base = dirs::config_dir()
18 .ok_or_else(|| anyhow::anyhow!("could not resolve config directory"))?;
19 Ok(base.join("flatland").join("session.json"))
20 }
21
22 pub fn load() -> anyhow::Result<Self> {
23 let path = Self::path()?;
24 let bytes = std::fs::read(&path)
25 .map_err(|_| anyhow::anyhow!("not logged in; run `flatland3 auth login`"))?;
26 Ok(serde_json::from_slice(&bytes)?)
27 }
28
29 pub fn save(&self) -> anyhow::Result<()> {
30 let path = Self::path()?;
31 if let Some(parent) = path.parent() {
32 std::fs::create_dir_all(parent)?;
33 }
34 std::fs::write(path, serde_json::to_vec_pretty(self)?)?;
35 Ok(())
36 }
37
38 pub fn remember_character(&mut self, character_id: Uuid) -> anyhow::Result<()> {
39 if self.last_character_id == Some(character_id) {
40 return Ok(());
41 }
42 self.last_character_id = Some(character_id);
43 self.save()
44 }
45}
46
47pub fn default_api_base() -> String {
48 std::env::var("FLATLAND_API_URL").unwrap_or_else(|_| "http://127.0.0.1:7380".into())
49}