videosdk-server-sdk 0.1.0

Rust server SDK for the VideoSDK v2 REST APIs
Documentation
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
//! Types shared across resources.

use std::collections::HashMap;

use serde::{Deserialize, Deserializer, Serialize};

/// HATEOAS-style links returned on many resources.
pub type ResourceLinks = HashMap<String, String>;

/// Deserializes an explicit JSON `null` as `T::default()`.
///
/// `#[serde(default)]` alone only covers a *missing* key — an explicit `null`
/// still fails with "invalid type: null". The API returns `null` where Go's
/// `encoding/json` would have silently produced a zero value, so every
/// defaulted field pairs this with `default`:
///
/// ```ignore
/// #[serde(default, deserialize_with = "null_to_default")]
/// pub name: String,
/// ```
pub(crate) fn null_to_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de> + Default,
{
    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
}

/// The plain `{message}` body returned by many action and delete endpoints.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MessageResponse {
    /// The server's confirmation message.
    pub message: String,
}

/// Defines an open string enum: a transparent newtype over a string, carrying
/// associated constants for the values the API documents today.
///
/// A closed `enum` would be nicer to match on, but it would also fail to
/// deserialize the moment the API returns a value this SDK predates — taking the
/// whole response down with it. These types round-trip anything.
macro_rules! string_enum {
    (
        $(#[$meta:meta])*
        $name:ident {
            $($(#[$variant_meta:meta])* $constant:ident => $value:literal),* $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, Hash, ::serde::Serialize, ::serde::Deserialize)]
        #[serde(transparent)]
        pub struct $name(::std::borrow::Cow<'static, str>);

        impl $name {
            $($(#[$variant_meta])* pub const $constant: Self =
                Self(::std::borrow::Cow::Borrowed($value));)*

            /// The value as it appears on the wire.
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl ::std::fmt::Display for $name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                f.write_str(&self.0)
            }
        }

        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                &self.0
            }
        }

        impl From<&str> for $name {
            fn from(value: &str) -> Self {
                Self(::std::borrow::Cow::Owned(value.to_string()))
            }
        }

        impl From<String> for $name {
            fn from(value: String) -> Self {
                Self(::std::borrow::Cow::Owned(value))
            }
        }
    };
}

pub(crate) use string_enum;

string_enum! {
    /// A VideoSDK region code, accepted as a room's geo-fence.
    ///
    /// Any region string is accepted — the API may add regions this SDK
    /// predates — so this is a string newtype rather than a closed enum. The
    /// associated constants enumerate the currently known regions.
    ///
    /// ```
    /// # use videosdk::Region;
    /// assert_eq!(Region::US001.as_str(), "us001");
    /// assert_eq!(Region::from("mars001").as_str(), "mars001");
    /// ```
    Region {
        /// `us001`
        US001 => "us001",
        /// `uk001`
        UK001 => "uk001",
        /// `sg001`
        SG001 => "sg001",
        /// `eu001`
        EU001 => "eu001",
        /// `uae001`
        UAE001 => "uae001",
        /// `in001`
        IN001 => "in001",
        /// `in002`
        IN002 => "in002",
        /// `in003`
        IN003 => "in003",
        /// `sg002`
        SG002 => "sg002",
        /// `us002`
        US002 => "us002",
        /// `aus001`
        AUS001 => "aus001",
        /// `dev1`
        DEV1 => "dev1",
    }
}

/* ---------------------------- composition layout ---------------------------- */

/// A composition layout style, as it appears on the wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum LayoutType {
    /// Highlights the active participant.
    Spotlight,
    /// A main stage with a sidebar of participants.
    Sidebar,
    /// An even grid of participants.
    Grid,
}

/// Which participant a layout prioritizes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum LayoutPriority {
    /// Prioritize whoever is speaking.
    Speaker,
    /// Prioritize the pinned participant.
    Pin,
}

/// A composition's orientation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Orientation {
    /// Taller than wide.
    Portrait,
    /// Wider than tall.
    Landscape,
}

/// A composition's theme.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Theme {
    /// A dark theme.
    Dark,
    /// A light theme.
    Light,
    /// The account's default theme.
    Default,
}

/// A recorder quality tier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CompositionQuality {
    /// Lowest bitrate.
    Low,
    /// Medium bitrate.
    Med,
    /// High bitrate.
    High,
    /// Highest bitrate.
    Ultra,
}

/// The wire layout configuration of a composition.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LayoutConfig {
    /// The layout style.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub kind: Option<LayoutType>,
    /// Which participant the layout prioritizes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<LayoutPriority>,
    /// The number of tiles in a grid layout: 0-25, defaulting to 25.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grid_size: Option<u32>,
}

/// The wire composition configuration, shared by recording, HLS and livestream.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompositionConfig {
    /// The layout configuration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub layout: Option<LayoutConfig>,
    /// The composition's orientation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub orientation: Option<Orientation>,
    /// The composition's theme.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub theme: Option<Theme>,
    /// The recorder quality tier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality: Option<CompositionQuality>,
}

impl CompositionConfig {
    /// Whether no field is set, i.e. this would serialize to `{}`.
    pub fn is_empty(&self) -> bool {
        self.layout.is_none()
            && self.orientation.is_none()
            && self.theme.is_none()
            && self.quality.is_none()
    }
}

/* -------------------------------- transcription ------------------------------ */

/// A post-call AI summary configuration. Requires transcription to be enabled.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SummaryConfig {
    /// Whether to generate a summary.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// A prompt steering the summary.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,
}

/// A real-time transcription configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TranscriptionConfig {
    /// Whether to transcribe.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// A post-call summary configuration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<SummaryConfig>,
}

/// The behavior applied when a composition fails.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OnFailureConfig {
    /// The action to take. Currently only `close-room` is supported.
    pub action: String,
    /// Seconds to wait before applying the action. Capped at 150, default 150.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wait_time: Option<u32>,
}

impl OnFailureConfig {
    /// Close the room if the composition fails.
    pub fn close_room(wait_time: Option<u32>) -> Self {
        Self {
            action: "close-room".to_string(),
            wait_time,
        }
    }
}

/* -------------------------------- file formats ------------------------------- */

/// The file format of a room or composite recording.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RecordingFileFormat {
    /// MPEG-4. The default.
    Mp4,
    /// WebM.
    Webm,
}

/// The file format of a participant recording.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ParticipantFileFormat {
    /// MPEG-4.
    Mp4,
    /// WebM. The default.
    Webm,
    /// An HLS playlist.
    M3u8,
}

/// The file format of a track recording.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TrackFileFormat {
    /// MPEG-4.
    Mp4,
    /// WebM. The default.
    Webm,
    /// An HLS playlist.
    M3u8,
    /// MP3 audio.
    Mp3,
}

/// The media kind of a track recording.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TrackKind {
    /// The participant's microphone.
    Audio,
    /// The participant's camera.
    Video,
    /// Audio shared with the screen.
    ScreenAudio,
    /// The shared screen.
    ScreenVideo,
}

/// A produced recording or output file.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecordingFile {
    /// Where the file can be downloaded.
    pub file_url: Option<String>,
    /// Any fields the server returned that this SDK does not model yet.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// A single webhook delivery attempt.
#[derive(Debug, Clone, Deserialize)]
pub struct WebhookDelivery {
    /// The event type that was delivered.
    #[serde(rename = "type")]
    pub kind: String,
    /// Whether the delivery succeeded.
    pub success: bool,
}

/// A summary of a resource's webhook delivery attempts.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WebhookDeliverySummary {
    /// How many deliveries were attempted.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub total_count: u32,
    /// How many deliveries succeeded.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub success_count: u32,
    /// The individual delivery attempts.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub data: Vec<WebhookDelivery>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn enums_use_the_wire_casing_the_api_expects() {
        assert_eq!(
            serde_json::to_value(LayoutType::Grid).unwrap(),
            json!("GRID")
        );
        assert_eq!(
            serde_json::to_value(LayoutPriority::Speaker).unwrap(),
            json!("SPEAKER")
        );
        assert_eq!(
            serde_json::to_value(Orientation::Portrait).unwrap(),
            json!("portrait")
        );
        assert_eq!(serde_json::to_value(Theme::Dark).unwrap(), json!("DARK"));
        assert_eq!(
            serde_json::to_value(CompositionQuality::Ultra).unwrap(),
            json!("ultra")
        );
        assert_eq!(
            serde_json::to_value(TrackKind::ScreenAudio).unwrap(),
            json!("screen_audio")
        );
        assert_eq!(
            serde_json::to_value(TrackFileFormat::M3u8).unwrap(),
            json!("m3u8")
        );
        assert_eq!(
            serde_json::to_value(RecordingFileFormat::Mp4).unwrap(),
            json!("mp4")
        );
    }

    #[test]
    fn layout_config_serializes_type_not_kind() {
        let config = LayoutConfig {
            kind: Some(LayoutType::Sidebar),
            priority: Some(LayoutPriority::Pin),
            grid_size: None,
        };
        assert_eq!(
            serde_json::to_value(config).unwrap(),
            json!({"type": "SIDEBAR", "priority": "PIN"})
        );
    }

    #[test]
    fn an_empty_composition_config_is_empty() {
        assert!(CompositionConfig::default().is_empty());
        assert!(!CompositionConfig {
            theme: Some(Theme::Light),
            ..Default::default()
        }
        .is_empty());
    }

    #[test]
    fn on_failure_helper_builds_the_documented_action() {
        assert_eq!(
            serde_json::to_value(OnFailureConfig::close_room(Some(30))).unwrap(),
            json!({"action": "close-room", "waitTime": 30})
        );
    }

    #[test]
    fn region_is_transparent_on_the_wire() {
        assert_eq!(serde_json::to_value(Region::IN002).unwrap(), json!("in002"));
        let parsed: Region = serde_json::from_value(json!("us001")).unwrap();
        assert_eq!(parsed, Region::US001);
    }

    #[test]
    fn an_unknown_region_round_trips() {
        let parsed: Region = serde_json::from_value(json!("future-region")).unwrap();
        assert_eq!(parsed.as_str(), "future-region");
        assert_eq!(
            serde_json::to_value(&parsed).unwrap(),
            json!("future-region")
        );
    }
}