use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::authentification::{Credentials, PartialProfile, Profile};
use crate::error::Result;
use crate::groups::NamedGroup;
use crate::http::{client, encode, ok};
use crate::private::authentification::Account;
static ROUTE: crate::route::Cell = crate::route::cell();
pub fn set_route(route: &str) {
crate::route::set(&ROUTE, route);
}
pub fn get_url() -> String {
crate::route::url(&ROUTE)
}
pub async fn authorize_token(token: &str) -> Result<Credentials> {
let response = client()
.post(format!("{}/authentification/authorize", get_url()))
.header("Authorization", format!("Token {token}"))
.send()
.await?;
let mut credentials: Credentials = ok(response).await?.json().await?;
credentials.token = token.to_string();
Ok(credentials)
}
pub async fn redeem_handoff(code: &str) -> Result<String> {
let response = client()
.post(format!("{}/authentification/handoff/redeem", get_url()))
.json(&json!({ "code": code }))
.send()
.await?;
Ok(ok(response).await?.text().await?)
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AccountQuery {
pub total: u64,
pub accounts: Vec<Account>,
}
impl AccountQuery {
pub fn from_json(json: &Value) -> AccountQuery {
AccountQuery {
total: json["total"].as_u64().unwrap_or(0),
accounts: json["accounts"]
.as_array()
.map(|rows| rows.iter().map(Account::from_json).collect())
.unwrap_or_default(),
}
}
}
pub async fn query(credentials: &Credentials, profile: &PartialProfile) -> Result<AccountQuery> {
let response = client()
.post(format!("{}/credentials/query", get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "email": profile.email, "displayName": profile.display_name }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(AccountQuery::from_json(&json))
}
#[derive(Debug, Clone, Deserialize)]
pub struct SessionToken {
pub token: String,
}
pub async fn session(credentials: &Credentials, email: &str) -> Result<SessionToken> {
let response = client()
.post(format!("{}/authentification/session", get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "email": email }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
#[derive(Debug, Clone)]
pub enum Grant {
Tier(String),
Permissions(Vec<String>),
Credit {
credit: f64,
api_key: Option<String>,
},
}
pub async fn grant(credentials: &Credentials, email: &str, update: &Grant) -> Result<Account> {
let body = match update {
Grant::Tier(tier) => json!({ "email": email, "tier": tier }),
Grant::Permissions(permissions) => json!({ "email": email, "permissions": permissions }),
Grant::Credit { credit, api_key } => {
let mut body = json!({ "email": email, "credit": credit });
if let Some(api_key) = api_key {
body["apiKey"] = json!(api_key);
}
body
}
};
let response = client()
.post(format!("{}/authentification/grant", get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&body)
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(Account::from_json(&json))
}
pub async fn grant_group(
credentials: &Credentials,
group: &str,
credit: f64,
) -> Result<NamedGroup> {
let response = client()
.post(format!("{}/authentification/grant", get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "group": group, "credit": credit }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(NamedGroup::from_json(&json))
}
pub async fn ban(credentials: &Credentials, profile: &Profile, banned: bool) -> Result<Account> {
let response = client()
.post(format!("{}/authentification/ban", get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "email": profile.email, "banned": banned }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(Account::from_json(&json))
}
pub async fn remove(credentials: &Credentials, email: &str) -> Result<bool> {
let response = client()
.delete(format!(
"{}/authentification?email={}",
get_url(),
encode(email)
))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
ok(response).await?;
Ok(true)
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ParrotSpreads {
pub llm_spread: f64,
pub embedder_spread: f64,
pub image_spread: f64,
pub video_spread: f64,
pub audio_spread: f64,
pub voice_spread: f64,
pub tts_spread: f64,
pub decision_spread: f64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct MarmotSpreads {
pub search_spread: f64,
pub proxy_datacenter_per_gb: f64,
pub proxy_residential_per_gb: f64,
pub render_per_page: f64,
pub puppeteer_per_action: f64,
pub x_tweet_spread: f64,
pub x_user_spread: f64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct MapsSpreads {
pub geocode_spread: f64,
pub places_spread: f64,
pub autocomplete_spread: f64,
pub routes_spread: f64,
pub weather_spread: f64,
pub tiles_per_1000_spread: f64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct TravelSpreads {
pub flights_spread: f64,
pub hotels_spread: f64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PaymentsSpreads {
pub card_percent: f64,
pub card_fixed: f64,
pub spread_percent: f64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct GlobalSpreads {
pub demo_budget_per_day: f64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Spreads {
pub parrot: ParrotSpreads,
pub marmot: MarmotSpreads,
pub maps: MapsSpreads,
pub travel: TravelSpreads,
pub payments: PaymentsSpreads,
pub global: GlobalSpreads,
}
pub async fn list_spread(credentials: &Credentials) -> Result<Spreads> {
let response = client()
.get(format!("{}/spread", get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SpreadApp {
Parrot,
Marmot,
Maps,
Travel,
Payments,
Global,
}
impl SpreadApp {
fn as_str(self) -> &'static str {
match self {
SpreadApp::Parrot => "parrot",
SpreadApp::Marmot => "marmot",
SpreadApp::Maps => "maps",
SpreadApp::Travel => "travel",
SpreadApp::Payments => "payments",
SpreadApp::Global => "global",
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct SpreadConfig {
pub app: SpreadApp,
pub config: HashMap<String, f64>,
}
pub async fn set_spread(
credentials: &Credentials,
app: SpreadApp,
config: &HashMap<String, f64>,
) -> Result<SpreadConfig> {
let response = client()
.put(format!("{}/spread/{}", get_url(), encode(app.as_str())))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "config": config }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
#[derive(Debug, Clone, Serialize)]
pub struct SpreadUsage {
pub app: String,
pub service: String,
pub day: String,
pub revenue: f64,
pub cost: f64,
pub credit: f64,
}
pub async fn usage_spread(credentials: &Credentials) -> Result<Vec<SpreadUsage>> {
let response = client()
.get(format!("{}/spread/usage", get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
let rows: Vec<Value> = ok(response).await?.json().await?;
let dollars = |row: &Value, key: &str| row[key].as_f64().unwrap_or(0.0) / 1_000_000.0;
Ok(rows
.iter()
.map(|row| SpreadUsage {
app: row["app"].as_str().unwrap_or_default().to_string(),
service: row["service"].as_str().unwrap_or_default().to_string(),
day: row["day"].as_str().unwrap_or_default().to_string(),
revenue: dollars(row, "revenueMicros"),
cost: dollars(row, "costMicros"),
credit: dollars(row, "creditMicros"),
})
.collect())
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddonDefinition {
pub id: String,
pub name: String,
pub stripe_price_id: String,
pub capabilities: Vec<String>,
pub active: bool,
}
pub async fn list_addons(credentials: &Credentials) -> Result<Vec<AddonDefinition>> {
let response = client()
.get(format!("{}/billing/admin/addons", get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}