use chrono::{DateTime, Utc};
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use serde_json::json;
use sha2::Sha256;
use crate::authentification::{CredentialsOrApiKey, Profile};
use crate::error::Result;
use crate::http::{client, encode, ok};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EventType {
#[serde(rename = "chat.message")]
ChatMessage,
#[serde(rename = "payment.succeeded")]
PaymentSucceeded,
#[serde(rename = "payment.expired")]
PaymentExpired,
#[serde(rename = "payment.refunded")]
PaymentRefunded,
#[serde(rename = "payment.disputed")]
PaymentDisputed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WebhookOwner {
Group(String),
Chat(String),
Key,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Webhook {
pub id: String,
pub url: String,
pub events: Vec<EventType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub creator: Option<Profile>,
pub created: DateTime<Utc>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Registration {
pub webhook: Webhook,
pub secret: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Delivery {
pub id: String,
pub r#type: EventType,
pub created: i64,
pub data: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Reaction {
pub emoji: String,
pub position: u32,
pub on: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatMessage {
pub chat_id: String,
pub chat_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub group: Option<String>,
pub position: u32,
pub author: Profile,
pub text: String,
#[serde(default)]
pub mentions: Vec<Profile>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reaction: Option<Reaction>,
pub created: i64,
}
pub async fn create(
authorization: &CredentialsOrApiKey,
owner: &WebhookOwner,
url: &str,
events: &[EventType],
secret: Option<&str>,
) -> Result<Registration> {
let response = client()
.post(format!("{}/webhooks", crate::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.json(&json!({ "owner": owner, "url": url, "events": events, "secret": secret }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn list(
authorization: &CredentialsOrApiKey,
owner: &WebhookOwner,
) -> Result<Vec<Webhook>> {
let response = client()
.post(format!("{}/webhooks/list", crate::get_url()))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.json(&json!({ "owner": owner }))
.send()
.await?;
Ok(ok(response).await?.json().await?)
}
pub async fn remove(authorization: &CredentialsOrApiKey, id: &str) -> Result<()> {
let response = client()
.delete(format!("{}/webhooks/{}", crate::get_url(), encode(id)))
.header(
"Authorization",
match authorization {
CredentialsOrApiKey::Credentials(credentials) => {
format!("Token {}", credentials.token)
}
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
},
)
.send()
.await?;
ok(response).await?;
Ok(())
}
pub async fn verify(
secret: &str,
body: &str,
signature: &str,
tolerance: Option<i64>,
) -> Result<bool> {
let mut timestamp = None;
let mut expected = None;
for piece in signature.split(',') {
if let Some((key, value)) = piece.split_once('=') {
match key.trim() {
"t" => timestamp = value.trim().parse::<i64>().ok(),
"v1" => expected = hex(value.trim()),
_ => {}
}
}
}
let (Some(timestamp), Some(expected)) = (timestamp, expected) else {
return Ok(false);
};
if (Utc::now().timestamp() - timestamp).abs() > tolerance.unwrap_or(300) {
return Ok(false);
}
let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(secret.as_bytes()) else {
return Ok(false);
};
mac.update(format!("{timestamp}.{body}").as_bytes());
Ok(mac.verify_slice(&expected).is_ok())
}
fn hex(text: &str) -> Option<Vec<u8>> {
if !text.len().is_multiple_of(2) {
return None;
}
(0..text.len())
.step_by(2)
.map(|at| u8::from_str_radix(text.get(at..at + 2)?, 16).ok())
.collect()
}