seven_client/
hooks.rs

1use crate::client::Client;
2use ureq::{Error, Request};
3use serde::{Deserialize};
4
5const ENDPOINT: &str = "hooks";
6
7pub enum EventType {
8    All,
9    DLR,
10    InboundSMS,
11    Tracking,
12    VoiceCall,
13    VoiceStatus,
14}
15
16impl Default for EventType {
17    fn default() -> Self {
18        panic!("Event type must be set");
19    }
20}
21
22#[derive(Deserialize)]
23pub struct Hook {
24    pub created: String,
25    pub event_type: String,
26    pub id: String,
27    pub request_method: String,
28    pub target_url: String,
29}
30
31#[derive(Deserialize)]
32pub struct HooksRead {
33    pub success: bool,
34    pub hooks: Vec<Hook>,
35}
36
37#[derive(Default)]
38pub struct HookSubscribeParams {
39    pub event_filter: Option<String>,
40    pub event_type: EventType,
41    pub request_method: Option<String>,
42    pub target_url: String,
43}
44
45#[derive(Deserialize)]
46pub struct HookSubscribeResponse {
47    pub id: Option<u32>,
48    pub success: bool,
49}
50
51pub struct HookUnsubscribeParams {
52    pub id: u32,
53}
54
55#[derive(Deserialize)]
56pub struct HookUnsubscribeResponse {
57    pub success: bool,
58}
59
60pub struct Hooks {
61    client: Client
62}
63
64impl Hooks {
65    pub fn new(client: Client) -> Self {
66        Hooks {
67            client,
68        }
69    }
70
71    fn request(&self, method: &str, action: &str) -> Request {
72        self.client.request(method, ENDPOINT).query("action", action)
73    }
74
75    pub fn read(&self) -> Result<HooksRead, Error> {
76        Ok(self.request("GET", "read").call()?.into_json::<HooksRead>()?)
77    }
78
79    pub fn subscribe(&self, params: HookSubscribeParams) -> Result<HookSubscribeResponse, Error> {
80        let event_type = match params.event_type {
81            EventType::All => {"all"}
82            EventType::DLR => {"dlr"}
83            EventType::InboundSMS => {"sms_mo"}
84            EventType::Tracking => {"tracking"}
85            EventType::VoiceCall => {"voice_call"}
86            EventType::VoiceStatus => {"voice_status"}
87        };
88        let res = self.request("POST", "subscribe")
89            .send_form(&[
90                ("event_type", event_type),
91                ("request_method", &*params.request_method.unwrap_or_default()),
92                ("target_url", &*params.target_url),
93            ])?
94            .into_json::<HookSubscribeResponse>()?;
95        Ok(res)
96    }
97
98    pub fn unsubscribe(&self, params: HookUnsubscribeParams) -> Result<HookUnsubscribeResponse, Error> {
99        Ok(self.request("POST", "unsubscribe")
100            .send_form(&[("id", &*params.id.to_string())])?
101            .into_json::<HookUnsubscribeResponse>()?
102        )
103    }
104}