1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
//! A fully generated, opinionated API client library for Zoom.
//!
//! ## API Details
//!
//! The Zoom API allows developers to access information from Zoom. You can use this API to build private services or public applications on the [Zoom App Marketplace](http://marketplace.zoom.us). To learn how to get your credentials and create private/public applications, read our [Authorization Guide](https://marketplace.zoom.us/docs/guides/authorization/credentials).
//! All endpoints are available via `https` and are located at `api.zoom.us/v2/`.
//!
//! For instance you can list all users on an account via `https://api.zoom.us/v2/users/`.
//!
//! [API Terms of Service](https://zoom.us/docs/en-us/zoom_api_license_and_tou.html)
//!
//! ### Contact
//!
//!
//! | name | url | email |
//! |----|----|----|
//! | Zoom Developers | <https://developer.zoom.us/> | developersupport@zoom.us |
//!
//! ### License
//!
//!
//! | name | url |
//! |----|----|
//! | MIT for OAS 2.0 | <https://opensource.org/licenses/MIT> |
//!
//!
//! ## Client Details
//!
//! This client is generated from the [Zoom OpenAPI
//! specs](https://marketplace.zoom.us/docs/api-reference/zoom-api/Zoom%20API.oas2.json) based on API spec version `2.0.0`. This way it will remain
//! up to date as features are added. The documentation for the crate is generated
//! along with the code to make this library easy to use.
//! //! To install the library, add the following to your `Cargo.toml` file.
//!
//! ```toml
//! [dependencies]
//! zoom_api = "0.2.0"
//! ```
//!
//! ## Basic example
//!
//! Typical use will require intializing a `Client`. This requires
//! a user agent string and set of credentials.
//!
//! ```
//! use zoom_api::Client;
//!
//! let zoom = Client::new(
//!     String::from("client-id"),
//!     String::from("client-secret"),
//!     String::from("redirect-uri"),
//!     String::from("token"),
//!     String::from("refresh-token"),
//! );
//! ```
//!
//! Alternatively, the library can search for most of the variables required for
//! the client in the environment:
//!
//! - `ZOOM_CLIENT_ID`
//! - `ZOOM_CLIENT_SECRET`
//! - `ZOOM_REDIRECT_URI`
//!
//! And then you can create a client from the environment.
//!
//! ```
//! use zoom_api::Client;
//!
//! let zoom = Client::new_from_env(String::from("token"), String::from("refresh-token"));
//! ```
//!
//! It is okay to pass empty values for `token` and `refresh_token`. In
//! the initial state of the client, you will not know these values.
//!
//! To start off a fresh client and get a `token` and `refresh_token`, use the following.
//!
//! ```
//! use zoom_api::Client;
//!
//! async fn do_call() {
//!     let mut zoom = Client::new_from_env("", "");
//!
//!     // Get the URL to request consent from the user.
//!     // You can optionally pass in scopes. If none are provided, then the
//!     // resulting URL will not have any scopes.
//!     let user_consent_url = zoom.user_consent_url(&["some-scope".to_string()]);
//!
//!     // In your redirect URL capture the code sent and our state.
//!     // Send it along to the request for the token.
//!     let code = "thing-from-redirect-url";
//!     let state = "state-from-redirect-url";
//!     let mut access_token = zoom.get_access_token(code, state).await.unwrap();
//!
//!     // You can additionally refresh the access token with the following.
//!     // You must have a refresh token to be able to call this function.
//!     access_token = zoom.refresh_access_token().await.unwrap();
//! }
//! ```
#![feature(async_stream)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::nonstandard_macro_braces)]
#![allow(clippy::large_enum_variant)]
#![allow(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]

pub mod accounts;
pub mod archiving;
pub mod billing;
pub mod chat_channels;
pub mod chat_channels_account_level;
pub mod chat_messages;
pub mod chatbot_messages;
pub mod cloud_recording;
pub mod common_area_phones;
pub mod contacts;
pub mod dashboards;
pub mod deprecated_api_endpoints;
pub mod devices;
pub mod groups;
pub mod im_chat;
pub mod im_groups;
pub mod meetings;
pub mod pac;
pub mod phone;
pub mod phone_auto_receptionists;
pub mod phone_blocked_list;
pub mod phone_call_queues;
pub mod phone_devices;
pub mod phone_reports;
pub mod phone_shared_line_groups;
pub mod phone_site;
pub mod reports;
pub mod roles;
pub mod rooms;
pub mod rooms_account;
pub mod rooms_devices;
pub mod rooms_location;
pub mod sip_connected_audio;
pub mod sip_phone;
#[cfg(test)]
mod tests;
pub mod tracking_field;
pub mod tsp;
pub mod types;
pub mod users;
#[doc(hidden)]
pub mod utils;
pub mod webinars;

use anyhow::{anyhow, Error, Result};

pub const DEFAULT_HOST: &str = "https://api.zoom.us/v2";

mod progenitor_support {
    use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};

    const PATH_SET: &AsciiSet = &CONTROLS
        .add(b' ')
        .add(b'"')
        .add(b'#')
        .add(b'<')
        .add(b'>')
        .add(b'?')
        .add(b'`')
        .add(b'{')
        .add(b'}');

    #[allow(dead_code)]
    pub(crate) fn encode_path(pc: &str) -> String {
        utf8_percent_encode(pc, PATH_SET).to_string()
    }
}

use std::env;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

const TOKEN_ENDPOINT: &str = "https://zoom.us/oauth/token";
const USER_CONSENT_ENDPOINT: &str = "https://zoom.us/oauth/authorize";

/// Entrypoint for interacting with the API client.
#[derive(Clone)]
pub struct Client {
    token: String,
    // This will expire within a certain amount of time as determined by the
    // expiration date passed back in the initial request.
    refresh_token: String,
    client_id: String,
    client_secret: String,
    redirect_uri: String,

    client: reqwest::Client,
}

#[derive(Debug, JsonSchema, Clone, Default, Serialize, Deserialize)]
pub struct AccessToken {
    #[serde(
        default,
        skip_serializing_if = "String::is_empty",
        deserialize_with = "crate::utils::deserialize_null_string::deserialize"
    )]
    pub token_type: String,

    #[serde(
        default,
        skip_serializing_if = "String::is_empty",
        deserialize_with = "crate::utils::deserialize_null_string::deserialize"
    )]
    pub access_token: String,
    #[serde(default)]
    pub expires_in: i64,

    #[serde(
        default,
        skip_serializing_if = "String::is_empty",
        deserialize_with = "crate::utils::deserialize_null_string::deserialize"
    )]
    pub refresh_token: String,
    #[serde(default, alias = "x_refresh_token_expires_in")]
    pub refresh_token_expires_in: i64,

    #[serde(
        default,
        skip_serializing_if = "String::is_empty",
        deserialize_with = "crate::utils::deserialize_null_string::deserialize"
    )]
    pub scope: String,
}

impl Client {
    /// Create a new Client struct. It takes a type that can convert into
    /// an &str (`String` or `Vec<u8>` for example). As long as the function is
    /// given a valid API key your requests will work.
    pub fn new<I, K, R, T, Q>(
        client_id: I,
        client_secret: K,
        redirect_uri: R,
        token: T,
        refresh_token: Q,
    ) -> Self
    where
        I: ToString,
        K: ToString,
        R: ToString,
        T: ToString,
        Q: ToString,
    {
        let client = reqwest::Client::builder().build();
        match client {
            Ok(c) => {
                // We do not refresh the access token here since we leave that up to the
                // user to do so they can re-save it to their database.
                // TODO: But in the future we should save the expires in date and refresh it
                // if it needs to be refreshed.
                //
                Client {
                    client_id: client_id.to_string(),
                    client_secret: client_secret.to_string(),
                    redirect_uri: redirect_uri.to_string(),
                    token: token.to_string(),
                    refresh_token: refresh_token.to_string(),

                    client: c,
                }
            }
            Err(e) => panic!("creating reqwest client failed: {:?}", e),
        }
    }

    /// Create a new Client struct from environment variables. It
    /// takes a type that can convert into
    /// an &str (`String` or `Vec<u8>` for example). As long as the function is
    /// given a valid API key and your requests will work.
    /// We pass in the token and refresh token to the client so if you are storing
    /// it in a database, you can get it first.
    pub fn new_from_env<T, R>(token: T, refresh_token: R) -> Self
    where
        T: ToString,
        R: ToString,
    {
        let client_id = env::var("ZOOM_CLIENT_ID").unwrap();
        let client_secret = env::var("ZOOM_CLIENT_SECRET").unwrap();
        let redirect_uri = env::var("ZOOM_REDIRECT_URI").unwrap();

        Client::new(client_id, client_secret, redirect_uri, token, refresh_token)
    }

    async fn url_and_auth(&self, uri: &str) -> Result<(reqwest::Url, Option<String>)> {
        let parsed_url = uri.parse::<reqwest::Url>();

        let auth = format!("Bearer {}", self.token);
        parsed_url.map(|u| (u, Some(auth))).map_err(Error::from)
    }

    async fn request<Out>(
        &self,
        method: reqwest::Method,
        uri: &str,
        body: Option<reqwest::Body>,
    ) -> Result<Out>
    where
        Out: serde::de::DeserializeOwned + 'static + Send,
    {
        let (url, auth) = self.url_and_auth(uri).await?;

        let instance = <&Client>::clone(&self);

        let mut req = instance.client.request(method, url);

        // Set the default headers.
        req = req.header(
            reqwest::header::ACCEPT,
            reqwest::header::HeaderValue::from_static("application/json"),
        );
        req = req.header(
            reqwest::header::CONTENT_TYPE,
            reqwest::header::HeaderValue::from_static("application/json"),
        );

        if let Some(auth_str) = auth {
            req = req.header(http::header::AUTHORIZATION, &*auth_str);
        }

        if let Some(body) = body {
            //println!("Body: {:?}", String::from_utf8(body.as_bytes().unwrap().to_vec()).unwrap());
            req = req.body(body);
        }
        //println!("Request: {:?}", &req);
        let response = req.send().await?;

        let status = response.status();

        let response_body = response.bytes().await?;

        if status.is_success() {
            //println!("response payload {}", String::from_utf8_lossy(&response_body));
            let parsed_response = if status == http::StatusCode::NO_CONTENT {
                serde_json::from_str("null")
            } else {
                serde_json::from_slice::<Out>(&response_body)
            };
            parsed_response.map_err(Error::from)
        } else {
            /*println!("error status: {:?}, response payload: {}",
                status,
                String::from_utf8_lossy(&response_body),
            );*/

            let error = if response_body.is_empty() {
                anyhow!("code: {}, empty response", status)
            } else {
                anyhow!(
                    "code: {}, error: {:?}",
                    status,
                    String::from_utf8_lossy(&response_body),
                )
            };

            Err(error)
        }
    }

    async fn request_entity<D>(
        &self,
        method: http::Method,
        uri: &str,
        body: Option<reqwest::Body>,
    ) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        let r = self.request(method, uri, body).await?;
        Ok(r)
    }

    /// Return a user consent url with an optional set of scopes.
    /// If no scopes are provided, they will not be passed in the url.
    pub fn user_consent_url(&self, scopes: &[String]) -> String {
        let state = uuid::Uuid::new_v4();

        let url = format!(
            "{}?client_id={}&response_type=code&redirect_uri={}&state={}",
            USER_CONSENT_ENDPOINT, self.client_id, self.redirect_uri, state
        );

        if scopes.is_empty() {
            return url;
        }

        // Add the scopes.
        format!("{}&scope={}", url, scopes.join(" "))
    }

    /// Refresh an access token from a refresh token. Client must have a refresh token
    /// for this to work.
    pub async fn refresh_access_token(&mut self) -> Result<AccessToken> {
        if self.refresh_token.is_empty() {
            anyhow!("refresh token cannot be empty");
        }

        let mut headers = reqwest::header::HeaderMap::new();
        headers.append(
            reqwest::header::ACCEPT,
            reqwest::header::HeaderValue::from_static("application/json"),
        );

        let params = [
            ("grant_type", "refresh_token"),
            ("refresh_token", &self.refresh_token),
            ("client_id", &self.client_id),
            ("client_secret", &self.client_secret),
            ("redirect_uri", &self.redirect_uri),
        ];
        let client = reqwest::Client::new();
        let resp = client
            .post(TOKEN_ENDPOINT)
            .headers(headers)
            .form(&params)
            .basic_auth(&self.client_id, Some(&self.client_secret))
            .send()
            .await
            .unwrap();

        // Unwrap the response.
        let t: AccessToken = resp.json().await.unwrap();

        self.token = t.access_token.to_string();
        self.refresh_token = t.refresh_token.to_string();

        Ok(t)
    }

    /// Get an access token from the code returned by the URL paramter sent to the
    /// redirect URL.
    pub async fn get_access_token(&mut self, code: &str, state: &str) -> Result<AccessToken> {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.append(
            reqwest::header::ACCEPT,
            reqwest::header::HeaderValue::from_static("application/json"),
        );

        let params = [
            ("grant_type", "authorization_code"),
            ("code", code),
            ("client_id", &self.client_id),
            ("client_secret", &self.client_secret),
            ("redirect_uri", &self.redirect_uri),
            ("state", state),
        ];
        let client = reqwest::Client::new();
        let resp = client
            .post(TOKEN_ENDPOINT)
            .headers(headers)
            .form(&params)
            .basic_auth(&self.client_id, Some(&self.client_secret))
            .send()
            .await
            .unwrap();

        // Unwrap the response.
        let t: AccessToken = resp.json().await.unwrap();

        self.token = t.access_token.to_string();
        self.refresh_token = t.refresh_token.to_string();

        Ok(t)
    }

    #[allow(dead_code)]
    async fn get<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        self.request_entity(
            http::Method::GET,
            &(DEFAULT_HOST.to_string() + uri),
            message,
        )
        .await
    }

    #[allow(dead_code)]
    async fn get_all_pages<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<Vec<D>>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        // TODO: implement this.
        self.request_entity(
            http::Method::GET,
            &(DEFAULT_HOST.to_string() + uri),
            message,
        )
        .await
    }

    #[allow(dead_code)]
    async fn post<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        self.request_entity(
            http::Method::POST,
            &(DEFAULT_HOST.to_string() + uri),
            message,
        )
        .await
    }

    #[allow(dead_code)]
    async fn patch<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        self.request_entity(
            http::Method::PATCH,
            &(DEFAULT_HOST.to_string() + uri),
            message,
        )
        .await
    }

    #[allow(dead_code)]
    async fn put<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        self.request_entity(
            http::Method::PUT,
            &(DEFAULT_HOST.to_string() + uri),
            message,
        )
        .await
    }

    #[allow(dead_code)]
    async fn delete<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        self.request_entity(
            http::Method::DELETE,
            &(DEFAULT_HOST.to_string() + uri),
            message,
        )
        .await
    }

    pub fn accounts(&self) -> accounts::Accounts {
        accounts::Accounts::new(self.clone())
    }

    pub fn archiving(&self) -> archiving::Archiving {
        archiving::Archiving::new(self.clone())
    }

    pub fn billing(&self) -> billing::Billing {
        billing::Billing::new(self.clone())
    }

    pub fn chat_channels(&self) -> chat_channels::ChatChannels {
        chat_channels::ChatChannels::new(self.clone())
    }

    pub fn chat_channels_account_level(
        &self,
    ) -> chat_channels_account_level::ChatChannelsAccountLevel {
        chat_channels_account_level::ChatChannelsAccountLevel::new(self.clone())
    }

    pub fn chat_messages(&self) -> chat_messages::ChatMessages {
        chat_messages::ChatMessages::new(self.clone())
    }

    pub fn chatbot_messages(&self) -> chatbot_messages::ChatbotMessages {
        chatbot_messages::ChatbotMessages::new(self.clone())
    }

    pub fn cloud_recording(&self) -> cloud_recording::CloudRecording {
        cloud_recording::CloudRecording::new(self.clone())
    }

    pub fn common_area_phones(&self) -> common_area_phones::CommonAreaPhones {
        common_area_phones::CommonAreaPhones::new(self.clone())
    }

    pub fn contacts(&self) -> contacts::Contacts {
        contacts::Contacts::new(self.clone())
    }

    pub fn dashboards(&self) -> dashboards::Dashboards {
        dashboards::Dashboards::new(self.clone())
    }

    pub fn deprecated_api_endpoints(&self) -> deprecated_api_endpoints::DeprecatedApiEndpoints {
        deprecated_api_endpoints::DeprecatedApiEndpoints::new(self.clone())
    }

    pub fn devices(&self) -> devices::Devices {
        devices::Devices::new(self.clone())
    }

    pub fn groups(&self) -> groups::Groups {
        groups::Groups::new(self.clone())
    }

    pub fn im_chat(&self) -> im_chat::ImChat {
        im_chat::ImChat::new(self.clone())
    }

    pub fn im_groups(&self) -> im_groups::ImGroups {
        im_groups::ImGroups::new(self.clone())
    }

    pub fn meetings(&self) -> meetings::Meetings {
        meetings::Meetings::new(self.clone())
    }

    pub fn pac(&self) -> pac::Pac {
        pac::Pac::new(self.clone())
    }

    pub fn phone(&self) -> phone::Phone {
        phone::Phone::new(self.clone())
    }

    pub fn phone_auto_receptionists(&self) -> phone_auto_receptionists::PhoneAutoReceptionists {
        phone_auto_receptionists::PhoneAutoReceptionists::new(self.clone())
    }

    pub fn phone_blocked_list(&self) -> phone_blocked_list::PhoneBlockedList {
        phone_blocked_list::PhoneBlockedList::new(self.clone())
    }

    pub fn phone_call_queues(&self) -> phone_call_queues::PhoneCallQueues {
        phone_call_queues::PhoneCallQueues::new(self.clone())
    }

    pub fn phone_devices(&self) -> phone_devices::PhoneDevices {
        phone_devices::PhoneDevices::new(self.clone())
    }

    pub fn phone_reports(&self) -> phone_reports::PhoneReports {
        phone_reports::PhoneReports::new(self.clone())
    }

    pub fn phone_shared_line_groups(&self) -> phone_shared_line_groups::PhoneSharedLineGroups {
        phone_shared_line_groups::PhoneSharedLineGroups::new(self.clone())
    }

    pub fn phone_site(&self) -> phone_site::PhoneSite {
        phone_site::PhoneSite::new(self.clone())
    }

    pub fn reports(&self) -> reports::Reports {
        reports::Reports::new(self.clone())
    }

    pub fn roles(&self) -> roles::Roles {
        roles::Roles::new(self.clone())
    }

    pub fn rooms(&self) -> rooms::Rooms {
        rooms::Rooms::new(self.clone())
    }

    pub fn rooms_account(&self) -> rooms_account::RoomsAccount {
        rooms_account::RoomsAccount::new(self.clone())
    }

    pub fn rooms_devices(&self) -> rooms_devices::RoomsDevices {
        rooms_devices::RoomsDevices::new(self.clone())
    }

    pub fn rooms_location(&self) -> rooms_location::RoomsLocation {
        rooms_location::RoomsLocation::new(self.clone())
    }

    pub fn sip_connected_audio(&self) -> sip_connected_audio::SipConnectedAudio {
        sip_connected_audio::SipConnectedAudio::new(self.clone())
    }

    pub fn sip_phone(&self) -> sip_phone::SipPhone {
        sip_phone::SipPhone::new(self.clone())
    }

    pub fn tracking_field(&self) -> tracking_field::TrackingField {
        tracking_field::TrackingField::new(self.clone())
    }

    pub fn tsp(&self) -> tsp::Tsp {
        tsp::Tsp::new(self.clone())
    }

    pub fn users(&self) -> users::Users {
        users::Users::new(self.clone())
    }

    pub fn webinars(&self) -> webinars::Webinars {
        webinars::Webinars::new(self.clone())
    }
}