use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde_json::{Map, Value};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
File(PathBuf),
Config { section: String, index: usize },
Runtime,
}
#[derive(Debug, Clone)]
pub struct Credential {
pub id: String,
pub provider: String,
pub source: Source,
pub disabled: bool,
pub label: String,
pub attributes: BTreeMap<String, String>,
pub metadata: Map<String, Value>,
pub revision: u64,
pub next_refresh_after: Option<std::time::SystemTime>,
}
impl Credential {
pub fn str(&self, key: &str) -> Option<&str> {
self.metadata.get(key).and_then(Value::as_str)
}
pub fn relay_session(channel: &str) -> Self {
let mut metadata = Map::new();
metadata.insert("email".into(), Value::String(channel.to_owned()));
Self {
id: channel.to_owned(),
provider: "aistudio".into(),
source: Source::Runtime,
disabled: false,
label: channel.to_owned(),
attributes: BTreeMap::from([("runtime_only".to_owned(), "true".to_owned())]),
metadata,
revision: 0,
next_refresh_after: None,
}
}
pub fn from_file(auth_dir: &Path, path: &Path, metadata: Map<String, Value>) -> Option<Self> {
let provider = metadata
.get("type")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
if provider.is_empty() || provider == "gemini-cli" {
return None;
}
let id = path
.strip_prefix(auth_dir)
.unwrap_or(path)
.to_string_lossy()
.into_owned();
let mut cred = Self {
id,
disabled: false,
label: String::new(),
provider,
source: Source::File(path.to_owned()),
attributes: BTreeMap::new(),
metadata,
revision: 0,
next_refresh_after: None,
};
cred.refresh_derived();
Some(cred)
}
pub fn refresh_derived(&mut self) {
self.disabled = self.metadata.get("disabled").and_then(Value::as_bool).unwrap_or(false);
self.label = match self.str("email") {
Some(email) if !email.is_empty() => email.to_owned(),
_ => self.provider.clone(),
};
}
}
#[derive(Debug, Clone, Default)]
pub struct MetadataPatch {
pub set: Map<String, Value>,
pub remove: Vec<String>,
}
impl MetadataPatch {
pub fn apply(&self, metadata: &mut Map<String, Value>) {
for key in &self.remove {
metadata.remove(key);
}
for (key, value) in &self.set {
metadata.insert(key.clone(), value.clone());
}
}
}