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
extern crate rustc_serialize;

use rand::Rng;
use rustc_serialize::hex::ToHex;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::time::{SystemTime, UNIX_EPOCH};
use thiserror::Error;

mod http_client;

static SERVER_URL: &str = "https://api.opentok.com";
static API_ENDPOINT_PATH_START: &str = "/v2/project/";

/// Unique session identifier.
pub type SessionId = String;

/// OpenTokError enumerates all possible errors returned by this library.
#[derive(Debug, Error, PartialEq)]
pub enum OpenTokError {
    #[error("Bad request {0}")]
    BadRequest(String),
    #[error("Cannot encode request")]
    EncodingError,
    #[error("OpenTok server error {0}")]
    ServerError(String),
    #[error("Unexpected response {0}")]
    UnexpectedResponse(String),
    #[error("Unknown error")]
    __Unknown,
}

impl From<surf::Error> for OpenTokError {
    fn from(error: surf::Error) -> OpenTokError {
        match error.status().into() {
            400..=499 => OpenTokError::BadRequest(error.to_string()),
            500..=599 => OpenTokError::ServerError(error.to_string()),
            _ => OpenTokError::__Unknown,
        }
    }
}

/// Determines whether a session will transmit streams using the OpenTok Media Router
/// or not.
#[derive(Debug, PartialEq)]
pub enum MediaMode {
    /// The session will try to transmit streams directly between clients.
    Relayed,
    /// The session will transmit streams using the OpenTok Media Router.
    Routed,
}

impl fmt::Display for MediaMode {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", format!("{:?}", self).to_lowercase())
    }
}

/// Determines whether a session is automatically archived or not.
/// Archiving is currently unsupported.
#[derive(Debug)]
pub enum ArchiveMode {
    /// The session will always be archived automatically.
    Always,
    /// A POST request to /archive is required to archive the session.
    /// Currently unsupported.
    Manual,
}

impl fmt::Display for ArchiveMode {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", format!("{:?}", self).to_lowercase())
    }
}

/// OpenTok Session options to be provided at Session creation time.
#[derive(Default)]
pub struct SessionOptions<'a> {
    /// An IP address that the OpenTok servers will use to situate the session in the global
    /// OpenTok network. If you do not set a location hint, the OpenTok servers will be based
    /// on the first client connecting to the session.
    pub location: Option<&'a str>,
    /// Determines whether the session will transmit streams using the OpenTok Media Router
    /// ("routed") or not ("relayed"). By default, the setting is "relayed".
    /// With the media_mode parameter set to "relayed", the session will attempt to transmit
    /// streams directly between clients. If clients cannot connect due to firewall restrictions,
    /// the session uses the OpenTok TURN server to relay audio-video streams.
    pub media_mode: Option<MediaMode>,
    /// Whether the session is automatically archived ("always") or not ("manual").
    /// By default, the setting is "manual". To archive the session (either automatically or not),
    /// you must set the media_mode parameter to "routed".
    /// Archiving is currently unsupported.
    pub archive_mode: Option<ArchiveMode>,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct CreateSessionBody<'a> {
    archive_mode: String,
    location: Option<&'a str>,
    #[serde(rename = "p2p.preference")]
    p2p_preference: &'a str,
}

impl<'a> From<SessionOptions<'a>> for CreateSessionBody<'a> {
    fn from(options: SessionOptions) -> CreateSessionBody {
        CreateSessionBody {
            archive_mode: options
                .archive_mode
                .map(|mode| mode.to_string())
                .unwrap_or_else(|| "manual".into()),
            location: options.location,
            p2p_preference: options
                .media_mode
                .map(|mode| {
                    if mode == MediaMode::Relayed {
                        "enabled"
                    } else {
                        "disabled"
                    }
                })
                .unwrap_or("disabled"),
        }
    }
}

#[derive(Deserialize)]
struct CreateSessionResponse {
    session_id: String,
}

#[derive(Debug)]
pub enum TokenRole {
    Publisher,
    Subscriber,
    Moderator,
}

impl fmt::Display for TokenRole {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", format!("{:?}", self).to_lowercase())
    }
}

#[derive(Debug)]
struct TokenData<'a> {
    session_id: &'a str,
    create_time: u64,
    expire_time: u64,
    nonce: u64,
    role: TokenRole,
}

impl<'a> TokenData<'a> {
    pub fn new(session_id: &'a str, role: TokenRole) -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards, Doc!")
            .as_secs();
        let mut rng = rand::thread_rng();
        Self {
            session_id,
            create_time: now,
            expire_time: now + (60 * 60 * 24),
            nonce: rng.gen::<u64>(),
            role,
        }
    }
}

impl<'a> fmt::Display for TokenData<'a> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(
            formatter,
            "session_id={}&create_time={}&expire_time={}&nonce={}&role={}",
            self.session_id, self.create_time, self.expire_time, self.nonce, self.role,
        )
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VideoType {
    Camera,
    Screen,
    Custom,
}

impl fmt::Display for VideoType {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", format!("{:?}", self).to_lowercase())
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
pub struct StreamInfo {
    id: String,
    video_type: VideoType,
    name: String,
    layout_class_list: Vec<String>,
}

/// Top level entry point exposing the OpenTok server SDK functionality.
/// Contains methods for creating OpenTok sessions, generating tokens and
/// getting information about streams.
pub struct OpenTok {
    api_key: String,
    api_secret: String,
}

impl OpenTok {
    /// Create a new instance of OpenTok. Requires an OpenTok API key and
    /// the API secret for your TokBox account. Do not publicly share your
    /// API secret.
    pub fn new(api_key: String, api_secret: String) -> Self {
        Self {
            api_key,
            api_secret,
        }
    }

    /// Creates a new OpenTok session.
    /// On success, a session ID is provided.
    pub async fn create_session<'a>(
        &self,
        options: SessionOptions<'a>,
    ) -> Result<String, OpenTokError> {
        let body: CreateSessionBody = options.into();
        let endpoint = format!("{}{}", SERVER_URL, "/session/create");
        let mut response =
            http_client::post(&endpoint, &self.api_key, &self.api_secret, &body).await?;
        let response_str = response.body_string().await?;
        let mut response: Vec<CreateSessionResponse> =
            serde_json::from_str::<Vec<CreateSessionResponse>>(&response_str)
                .map_err(|_| OpenTokError::UnexpectedResponse(response_str.clone()))?;
        assert_eq!(response.len(), 1);
        match response.pop() {
            Some(session) => Ok(session.session_id),
            None => Err(OpenTokError::UnexpectedResponse(response_str)),
        }
    }

    pub fn generate_token(&self, session_id: &str, role: TokenRole) -> String {
        let token_data = TokenData::new(session_id, role);
        let signed = hmacsha1::hmac_sha1(
            self.api_secret.as_bytes(),
            token_data.to_string().as_bytes(),
        )
        .to_hex();
        let decoded = format!("partner_id={}&sig={}:{}", self.api_key, signed, token_data);
        let encoded = base64::encode(decoded);
        format!("T1=={}", encoded)
    }

    pub async fn get_stream_info(
        &self,
        session_id: &str,
        stream_id: &str,
    ) -> Result<StreamInfo, OpenTokError> {
        let endpoint = format!(
            "{}{}{}/session/{}/stream/{}",
            SERVER_URL, API_ENDPOINT_PATH_START, self.api_key, session_id, stream_id
        );
        let mut response = http_client::get(&endpoint, &self.api_key, &self.api_secret).await?;
        let response_str = response.body_string().await?;
        serde_json::from_str::<StreamInfo>(&response_str)
            .map_err(|_| OpenTokError::UnexpectedResponse(response_str.clone()))
    }
}

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

    use futures::executor::LocalPool;
    use opentok::utils::common::Credentials;
    use opentok::utils::publisher::Publisher;
    use std::env;

    #[test]
    fn test_create_session_invalid_credentials() {
        let opentok = OpenTok::new("sancho".into(), "quijote".into());
        let mut pool = LocalPool::new();
        assert!(pool
            .run_until(opentok.create_session(SessionOptions::default()))
            .is_err());
    }

    #[test]
    fn test_create_session() {
        let api_key = env::var("OPENTOK_KEY").unwrap();
        let api_secret = env::var("OPENTOK_SECRET").unwrap();
        let opentok = OpenTok::new(api_key, api_secret);
        let mut pool = LocalPool::new();
        let session_id = pool
            .run_until(opentok.create_session(SessionOptions::default()))
            .unwrap();
        assert!(!session_id.is_empty());
    }

    #[test]
    fn test_generate_token() {
        let api_key = env::var("OPENTOK_KEY").unwrap();
        let api_secret = env::var("OPENTOK_SECRET").unwrap();
        let opentok = OpenTok::new(api_key, api_secret);
        let mut pool = LocalPool::new();
        let session_id = pool
            .run_until(opentok.create_session(SessionOptions::default()))
            .unwrap();
        assert!(!session_id.is_empty());
        let token = opentok.generate_token(&session_id, TokenRole::Publisher);
        assert!(!token.is_empty());
    }

    #[test]
    fn test_get_stream_info() {
        let api_key = env::var("OPENTOK_KEY").unwrap();
        let api_secret = env::var("OPENTOK_SECRET").unwrap();
        let opentok = OpenTok::new(api_key.clone(), api_secret);
        let mut pool = LocalPool::new();
        let session_id = pool
            .run_until(opentok.create_session(SessionOptions::default()))
            .unwrap();
        assert!(!session_id.is_empty());
        let token = opentok.generate_token(&session_id, TokenRole::Publisher);
        assert!(!token.is_empty());

        opentok::init().unwrap();

        let publisher = Publisher::new(
            Credentials {
                api_key,
                session_id: session_id.clone(),
                token,
            },
            Some(Box::new(move |publisher, stream_id| {
                let mut pool = LocalPool::new();
                let stream_info = pool
                    .run_until(opentok.get_stream_info(&session_id, &stream_id))
                    .unwrap();
                assert_eq!(stream_info.id, stream_id);
                publisher.stop();
            })),
            None,
        );

        publisher.run().unwrap();

        opentok::deinit().unwrap();
    }
}