syncable_cli/telemetry/
user.rs1use dirs::config_dir;
2use serde::{Deserialize, Serialize};
3use std::fs;
4use std::path::PathBuf;
5use uuid::Uuid;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct UserId {
9 pub id: String,
10 pub first_seen: chrono::DateTime<chrono::Utc>,
11}
12
13impl UserId {
14 pub fn load_or_create() -> Result<Self, Box<dyn std::error::Error>> {
15 let config_path = Self::get_user_id_path()?;
16
17 if config_path.exists() {
19 let content = fs::read_to_string(&config_path)?;
20 let user_id: UserId = serde_json::from_str(&content)?;
21 Ok(user_id)
22 } else {
23 let user_id = UserId {
25 id: Uuid::new_v4().to_string(),
26 first_seen: chrono::Utc::now(),
27 };
28
29 if let Some(parent) = config_path.parent() {
31 fs::create_dir_all(parent)?;
32 }
33 let content = serde_json::to_string_pretty(&user_id)?;
34 fs::write(&config_path, content)?;
35
36 Ok(user_id)
37 }
38 }
39
40 fn get_user_id_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
41 let config_dir = config_dir().ok_or("Could not determine config directory")?;
42 Ok(config_dir.join("syncable-cli").join("user_id"))
43 }
44}