1use chrono::{DateTime, Utc};
2use hmac::{Hmac, Mac};
3use serde::{Deserialize, Serialize};
4use serde_json::json;
5use sha2::Sha256;
6
7use crate::authentification::{CredentialsOrApiKey, Profile};
8use crate::error::Result;
9use crate::http::{client, encode, ok};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14pub enum EventType {
15 #[serde(rename = "chat.message")]
16 ChatMessage,
17 #[serde(rename = "payment.succeeded")]
18 PaymentSucceeded,
19 #[serde(rename = "payment.expired")]
20 PaymentExpired,
21 #[serde(rename = "payment.refunded")]
22 PaymentRefunded,
23 #[serde(rename = "payment.disputed")]
24 PaymentDisputed,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "camelCase")]
30pub enum WebhookOwner {
31 Group(String),
32 Chat(String),
33 Key,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
38#[serde(rename_all = "camelCase")]
39pub struct Webhook {
40 pub id: String,
41
42 pub url: String,
43 pub events: Vec<EventType>,
44
45 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub creator: Option<Profile>,
49 pub created: DateTime<Utc>,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct Registration {
55 pub webhook: Webhook,
56 pub secret: String,
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct Delivery {
62 pub id: String,
63 pub r#type: EventType,
64 pub created: i64,
66 pub data: serde_json::Value,
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct Reaction {
72 pub emoji: String,
73 pub position: u32,
75 pub on: bool,
76}
77
78#[derive(Debug, Clone, Serialize, Deserialize)]
81#[serde(rename_all = "camelCase")]
82pub struct ChatMessage {
83 pub chat_id: String,
84 pub chat_name: String,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub group: Option<String>,
87 pub position: u32,
88
89 pub author: Profile,
90 pub text: String,
91 #[serde(default)]
93 pub mentions: Vec<Profile>,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub reaction: Option<Reaction>,
97
98 pub created: i64,
100}
101
102pub async fn create(
106 authorization: &CredentialsOrApiKey,
107 owner: &WebhookOwner,
108 url: &str,
109 events: &[EventType],
110 secret: Option<&str>,
111) -> Result<Registration> {
112 let response = client()
113 .post(format!("{}/webhooks", crate::get_url()))
114 .header(
115 "Authorization",
116 match authorization {
117 CredentialsOrApiKey::Credentials(credentials) => {
118 format!("Token {}", credentials.token)
119 }
120 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
121 },
122 )
123 .json(&json!({ "owner": owner, "url": url, "events": events, "secret": secret }))
124 .send()
125 .await?;
126 Ok(ok(response).await?.json().await?)
127}
128
129pub async fn list(
131 authorization: &CredentialsOrApiKey,
132 owner: &WebhookOwner,
133) -> Result<Vec<Webhook>> {
134 let response = client()
135 .post(format!("{}/webhooks/list", crate::get_url()))
136 .header(
137 "Authorization",
138 match authorization {
139 CredentialsOrApiKey::Credentials(credentials) => {
140 format!("Token {}", credentials.token)
141 }
142 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
143 },
144 )
145 .json(&json!({ "owner": owner }))
146 .send()
147 .await?;
148 Ok(ok(response).await?.json().await?)
149}
150
151pub async fn remove(authorization: &CredentialsOrApiKey, id: &str) -> Result<()> {
152 let response = client()
153 .delete(format!("{}/webhooks/{}", crate::get_url(), encode(id)))
154 .header(
155 "Authorization",
156 match authorization {
157 CredentialsOrApiKey::Credentials(credentials) => {
158 format!("Token {}", credentials.token)
159 }
160 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
161 },
162 )
163 .send()
164 .await?;
165 ok(response).await?;
166 Ok(())
167}
168
169pub async fn verify(
174 secret: &str,
175 body: &str,
176 signature: &str,
177 tolerance: Option<i64>,
178) -> Result<bool> {
179 let mut timestamp = None;
180 let mut expected = None;
181 for piece in signature.split(',') {
182 if let Some((key, value)) = piece.split_once('=') {
183 match key.trim() {
184 "t" => timestamp = value.trim().parse::<i64>().ok(),
185 "v1" => expected = hex(value.trim()),
186 _ => {}
187 }
188 }
189 }
190 let (Some(timestamp), Some(expected)) = (timestamp, expected) else {
191 return Ok(false);
192 };
193 if (Utc::now().timestamp() - timestamp).abs() > tolerance.unwrap_or(300) {
194 return Ok(false);
195 }
196 let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(secret.as_bytes()) else {
197 return Ok(false);
198 };
199 mac.update(format!("{timestamp}.{body}").as_bytes());
200 Ok(mac.verify_slice(&expected).is_ok())
201}
202
203fn hex(text: &str) -> Option<Vec<u8>> {
204 if !text.len().is_multiple_of(2) {
205 return None;
206 }
207 (0..text.len())
208 .step_by(2)
209 .map(|at| u8::from_str_radix(text.get(at..at + 2)?, 16).ok())
210 .collect()
211}