use std::ops::Deref;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::authentification::Credentials;
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,
}
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",
}
}
}
#[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)]
pub enum PlatformAccount {
Google(Google),
Slack(Slack),
Discord(Discord),
Twilio(Twilio),
Microsoft(Microsoft),
WhatsApp(WhatsApp),
}
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,
}
}
}
fn wrap_account(authorization: &Credentials, platform: Platform, raw: &Value) -> PlatformAccount {
match platform {
Platform::Google => PlatformAccount::Google(Google::new(authorization, raw)),
Platform::Slack => PlatformAccount::Slack(Slack::new(authorization, raw)),
Platform::Discord => PlatformAccount::Discord(Discord::new(authorization, raw)),
Platform::Twilio => PlatformAccount::Twilio(Twilio::new(authorization, raw)),
Platform::Microsoft => PlatformAccount::Microsoft(Microsoft::new(authorization, raw)),
Platform::WhatsApp => PlatformAccount::WhatsApp(WhatsApp::new(authorization, raw)),
}
}
pub async fn link_platform(credentials: &Credentials, integration: Platform) -> Result<String> {
let response = client()
.post(format!("{}/integrations/link", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.json(&json!({ "integration": integration }))
.send()
.await?;
let value: Value = ok(response).await?.json().await?;
value["url"]
.as_str()
.map(str::to_string)
.ok_or_else(|| Error::Message("Invalid link response.".into()))
}
pub async fn get_accounts(credentials: &Credentials) -> Result<Vec<PlatformAccount>> {
let response = client()
.get(format!("{}/integrations/accounts", crate::get_url()))
.header("Authorization", format!("Token {}", credentials.token))
.send()
.await?;
let json: Vec<Value> = ok(response).await?.json().await?;
Ok(json
.iter()
.filter_map(|raw| {
let platform: Platform = serde_json::from_value(raw["platform"].clone()).ok()?;
Some(wrap_account(credentials, platform, raw))
})
.collect())
}