use std::ops::Deref;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::authentification::Credentials;
use crate::billing::PageQuery;
use crate::error::{Error, Result};
use crate::http::{client, encode, ok};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Platform {
#[serde(rename = "GOOGLE")]
Google,
#[serde(rename = "SLACK")]
Slack,
#[serde(rename = "DISCORD")]
Discord,
#[serde(rename = "TWILIO")]
Twilio,
#[serde(rename = "MICROSOFT")]
Microsoft,
#[serde(rename = "WHATSAPP")]
WhatsApp,
#[serde(rename = "GITHUB")]
GitHub,
}
impl Platform {
fn as_str(self) -> &'static str {
match self {
Platform::Google => "GOOGLE",
Platform::Slack => "SLACK",
Platform::Discord => "DISCORD",
Platform::Twilio => "TWILIO",
Platform::Microsoft => "MICROSOFT",
Platform::WhatsApp => "WHATSAPP",
Platform::GitHub => "GITHUB",
}
}
}
#[derive(Debug, Clone)]
pub struct Account {
pub authorization: Credentials,
pub platform: Platform,
pub authorized: bool,
pub created_at: DateTime<Utc>,
pub id: String,
}
impl Account {
fn new(authorization: &Credentials, platform: Platform, raw: &Value) -> Self {
Account {
authorization: authorization.clone(),
platform,
authorized: raw["authorized"].as_bool().unwrap_or(false),
created_at: raw["createdAt"]
.as_str()
.and_then(|value| DateTime::parse_from_rfc3339(value).ok())
.map(|value| value.with_timezone(&Utc))
.unwrap_or_default(),
id: raw["id"].as_str().unwrap_or_default().to_string(),
}
}
pub async fn unlink(&self) -> Result<()> {
let response = client()
.delete(format!(
"{}/integrations/accounts/{}?platform={}",
crate::get_url(),
encode(&self.id),
encode(self.platform.as_str())
))
.header(
"Authorization",
format!("Token {}", self.authorization.token),
)
.send()
.await?;
ok(response).await?;
Ok(())
}
}
fn strings(raw: &Value, key: &str) -> Vec<String> {
raw[key]
.as_array()
.map(|values| {
values
.iter()
.filter_map(|value| value.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default()
}
fn string(raw: &Value, key: &str) -> String {
raw[key].as_str().unwrap_or_default().to_string()
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Demographic {
pub age_range: [f64; 2],
pub gender: String,
pub percentage: f64,
}
#[derive(Debug, Clone)]
pub struct Google {
account: Account,
pub email: String,
pub scopes: Vec<String>,
}
impl Google {
fn new(authorization: &Credentials, raw: &Value) -> Self {
Google {
account: Account::new(authorization, Platform::Google, raw),
email: string(raw, "email"),
scopes: strings(raw, "scopes"),
}
}
pub async fn get_demographics(&self) -> Result<Vec<Demographic>> {
let response = client()
.post(format!(
"{}/integrations/google/youtube/demographics",
crate::get_url()
))
.header(
"Authorization",
format!("Token {}", self.authorization.token),
)
.json(&json!({ "accountId": self.id }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
}
impl Deref for Google {
type Target = Account;
fn deref(&self) -> &Account {
&self.account
}
}
#[derive(Debug, Clone)]
pub struct Slack {
account: Account,
pub email: String,
pub scopes: Vec<String>,
}
impl Slack {
fn new(authorization: &Credentials, raw: &Value) -> Self {
Slack {
account: Account::new(authorization, Platform::Slack, raw),
email: string(raw, "email"),
scopes: strings(raw, "scopes"),
}
}
}
impl Deref for Slack {
type Target = Account;
fn deref(&self) -> &Account {
&self.account
}
}
#[derive(Debug, Clone)]
pub struct Discord {
account: Account,
pub handle: String,
}
impl Discord {
fn new(authorization: &Credentials, raw: &Value) -> Self {
Discord {
account: Account::new(authorization, Platform::Discord, raw),
handle: string(raw, "handle"),
}
}
}
impl Deref for Discord {
type Target = Account;
fn deref(&self) -> &Account {
&self.account
}
}
#[derive(Debug, Clone)]
pub struct Twilio {
account: Account,
pub phone: String,
}
impl Twilio {
fn new(authorization: &Credentials, raw: &Value) -> Self {
Twilio {
account: Account::new(authorization, Platform::Twilio, raw),
phone: string(raw, "phone"),
}
}
}
impl Deref for Twilio {
type Target = Account;
fn deref(&self) -> &Account {
&self.account
}
}
#[derive(Debug, Clone)]
pub struct Microsoft {
account: Account,
pub email: String,
pub scopes: Vec<String>,
}
impl Microsoft {
fn new(authorization: &Credentials, raw: &Value) -> Self {
Microsoft {
account: Account::new(authorization, Platform::Microsoft, raw),
email: string(raw, "email"),
scopes: strings(raw, "scopes"),
}
}
}
impl Deref for Microsoft {
type Target = Account;
fn deref(&self) -> &Account {
&self.account
}
}
#[derive(Debug, Clone)]
pub struct WhatsApp {
account: Account,
pub phone: String,
}
impl WhatsApp {
fn new(authorization: &Credentials, raw: &Value) -> Self {
WhatsApp {
account: Account::new(authorization, Platform::WhatsApp, raw),
phone: string(raw, "phone"),
}
}
}
impl Deref for WhatsApp {
type Target = Account;
fn deref(&self) -> &Account {
&self.account
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GitHubRepository {
pub name: String,
pub url: String,
pub private: bool,
pub branch: String,
pub writable: bool,
}
impl GitHubRepository {
pub fn from_json(json: &Value) -> GitHubRepository {
GitHubRepository {
name: string(json, "name"),
url: string(json, "url"),
private: json["private"].as_bool() == Some(true),
branch: string(json, "branch"),
writable: json["writable"].as_bool() == Some(true),
}
}
}
#[derive(Debug, Clone)]
pub struct GitHub {
account: Account,
pub handle: String,
pub install_url: String,
}
impl GitHub {
fn new(authorization: &Credentials, raw: &Value) -> Self {
GitHub {
account: Account::new(authorization, Platform::GitHub, raw),
handle: string(raw, "handle"),
install_url: string(raw, "installUrl"),
}
}
pub async fn repositories(&self, query: PageQuery) -> Result<Vec<GitHubRepository>> {
let response = client()
.post(format!(
"{}/integrations/github/repositories",
crate::get_url()
))
.header(
"Authorization",
format!("Token {}", self.authorization.token),
)
.json(&json!({ "accountId": self.id, "cursor": query.cursor, "max": query.max }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Ok(json
.as_array()
.into_iter()
.flatten()
.map(GitHubRepository::from_json)
.collect())
}
}
impl Deref for GitHub {
type Target = Account;
fn deref(&self) -> &Account {
&self.account
}
}
#[derive(Debug, Clone)]
pub enum PlatformAccount {
Google(Google),
Slack(Slack),
Discord(Discord),
Twilio(Twilio),
Microsoft(Microsoft),
WhatsApp(WhatsApp),
GitHub(GitHub),
}
impl Deref for PlatformAccount {
type Target = Account;
fn deref(&self) -> &Account {
match self {
PlatformAccount::Google(account) => account,
PlatformAccount::Slack(account) => account,
PlatformAccount::Discord(account) => account,
PlatformAccount::Twilio(account) => account,
PlatformAccount::Microsoft(account) => account,
PlatformAccount::WhatsApp(account) => account,
PlatformAccount::GitHub(account) => account,
}
}
}
impl PlatformAccount {
pub fn from_json(json: &Value, authorization: &Credentials) -> Result<PlatformAccount> {
let platform: Platform = serde_json::from_value(json["platform"].clone())
.map_err(|_| Error::Message(format!("Unknown platform {}.", json["platform"])))?;
Ok(match platform {
Platform::Google => PlatformAccount::Google(Google::new(authorization, json)),
Platform::Slack => PlatformAccount::Slack(Slack::new(authorization, json)),
Platform::Discord => PlatformAccount::Discord(Discord::new(authorization, json)),
Platform::Twilio => PlatformAccount::Twilio(Twilio::new(authorization, json)),
Platform::Microsoft => PlatformAccount::Microsoft(Microsoft::new(authorization, json)),
Platform::WhatsApp => PlatformAccount::WhatsApp(WhatsApp::new(authorization, json)),
Platform::GitHub => PlatformAccount::GitHub(GitHub::new(authorization, json)),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlatformBrand {
pub id: Platform,
pub name: String,
pub logo: String,
}
impl PlatformBrand {
pub fn from_json(json: &Value) -> Result<PlatformBrand> {
Ok(PlatformBrand {
id: serde_json::from_value(json["id"].clone())
.map_err(|_| Error::Message(format!("Unknown platform {}.", json["id"])))?,
name: string(json, "name"),
logo: string(json, "logo"),
})
}
}
#[derive(Debug, Clone)]
pub struct Accounts {
pub platforms: Vec<PlatformBrand>,
pub accounts: Vec<PlatformAccount>,
}
impl Accounts {
pub fn from_json(json: &Value, authorization: &Credentials) -> Result<Accounts> {
let list = |key: &str| json[key].as_array().cloned().unwrap_or_default();
Ok(Accounts {
platforms: list("platforms")
.iter()
.map(PlatformBrand::from_json)
.collect::<Result<_>>()?,
accounts: list("accounts")
.iter()
.map(|account| PlatformAccount::from_json(account, authorization))
.collect::<Result<_>>()?,
})
}
}
#[derive(Debug, Clone)]
pub enum LinkOutcome {
Linked(Box<PlatformAccount>),
Cancelled,
Failed(String),
}
impl LinkOutcome {
pub fn from_json(json: &Value, authorization: &Credentials) -> Result<LinkOutcome> {
match json["outcome"].as_str() {
Some("linked") => Ok(LinkOutcome::Linked(Box::new(PlatformAccount::from_json(
&json["account"],
authorization,
)?))),
Some("cancelled") => Ok(LinkOutcome::Cancelled),
Some("failed") => Ok(LinkOutcome::Failed(string(json, "reason"))),
_ => Err(Error::Message(format!(
"Unknown link outcome {}.",
json["outcome"]
))),
}
}
}
fn landed_claim(landed: &str, state: &str) -> Option<String> {
let landed = reqwest::Url::parse(landed).ok()?;
let (landed_state, claim) = landed
.fragment()?
.strip_prefix("fauna-link=")?
.split_once('.')?;
(landed_state == state).then(|| claim.to_string())
}
pub async fn link_platform<F, Fut>(
credentials: &Credentials,
integration: Platform,
return_to: &str,
open: F,
) -> Result<LinkOutcome>
where
F: FnOnce(String) -> Fut,
Fut: Future<Output = String>,
{
let response = client()
.post(format!("{}/integrations/link", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "integration": integration, "returnTo": return_to }))
.send()
.await?;
let link: Value = ok(response).await?.json().await?;
let (Some(url), Some(state)) = (link["url"].as_str(), link["state"].as_str()) else {
return Err(Error::Message("Invalid link response.".into()));
};
let landed = open(url.to_string()).await;
finish_link(credentials, state, landed_claim(&landed, state).as_deref()).await
}
pub async fn finish_link(
credentials: &Credentials,
state: &str,
claim: Option<&str>,
) -> Result<LinkOutcome> {
let response = client()
.post(format!("{}/integrations/link/finish", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "state": state, "claim": claim }))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
LinkOutcome::from_json(&json, credentials)
}
pub async fn get_accounts(credentials: &Credentials) -> Result<Accounts> {
let response = client()
.get(format!("{}/integrations/accounts", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
let json: Value = ok(response).await?.json().await?;
Accounts::from_json(&json, credentials)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_claim_only_for_its_own_link() {
let landed = "https://app.faunakit.com/account?tab=1#fauna-link=abc.claim123";
assert_eq!(landed_claim(landed, "abc").as_deref(), Some("claim123"));
assert_eq!(landed_claim(landed, "xyz"), None);
assert_eq!(
landed_claim("https://app.faunakit.com/#fauna-link=abc", "abc"),
None
);
assert_eq!(
landed_claim("https://app.faunakit.com/account", "abc"),
None
);
assert_eq!(landed_claim("not a url", "abc"), None);
}
}