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
mod api;
pub(crate) mod formats;

use futures::channel::mpsc;
use futures::*;

use crate::common::{PhantomId, SocketInfo};
use crate::error;

pub use formats::{
    AnswerQuery, AnswerResponse, AnswerResponseParams, CallQuery, CallResponse, Constraints,
    MediaConnectionIdWrapper, MediaConnectionStatus, MediaParams, RedirectParameters, SsrcPair,
};
use formats::{MediaConnectionId, MediaId, RtcpId};

/// Shows DataConnection events.
///
/// It's response from GET /media/connections/{media_connection_id}/events
///
/// [API](http://35.200.46.204/#/3.media/media_connection_event)
#[derive(Debug, PartialEq, PartialOrd)]
pub enum MediaConnectionEventEnum {
    READY(MediaConnectionId),
    STREAM(MediaConnectionId),
    CLOSE(MediaConnectionId),
    ERROR((MediaConnectionId, String)),
}

/// Have WebRTC Gateway open a socket for feeding media.
///
/// This API need to identify whether the media is video or audio.
/// If is_video is true, it's video. Otherwise, it's audio.
///
/// It's bindings for POST /media.
///
/// [API](http://35.200.46.204/#/3.media/media)
///
/// # Examples
/// ```
/// use skyway_webrtc_gateway_api::media::open_media_socket;
///
/// async fn example() {
///     let result = open_media_socket(true).await; //video
///     let result = open_media_socket(false).await; //audio
/// }
/// ```
pub async fn open_media_socket(is_video: bool) -> Result<SocketInfo<MediaId>, error::Error> {
    let base_url = super::base_url();
    api::create_media(base_url, is_video).await
}

/// Have WebRTC Gateway close a media socket.
///
/// It's bindings for DELETE /media/{media_id}
///
/// [API](http://35.200.46.204/#/3.media/streams_delete)
///
/// # Examples
/// ```
/// use skyway_webrtc_gateway_api::media::delete_media;
/// use skyway_webrtc_gateway_api::prelude::MediaId;
///
/// async fn example() {
///     let media_id = MediaId::new("vi-example");
///     let result = delete_media(&media_id).await;
/// }
/// ```
pub async fn delete_media(media_id: &MediaId) -> Result<(), error::Error> {
    let base_url = super::base_url();
    api::delete_media(base_url, media_id.as_str()).await
}

/// Have WebRTC Gateway open a socket for feeding rtcp.
///
/// It's bindings for POST /media/rtcp.
///
/// [API](http://35.200.46.204/#/3.media/media_rtcp_create)
///
/// # Examples
/// ```
/// use skyway_webrtc_gateway_api::media::open_rtcp_socket;
///
/// async fn example() {
///     let result = open_rtcp_socket().await;
/// }
/// ```
pub async fn open_rtcp_socket() -> Result<SocketInfo<RtcpId>, error::Error> {
    let base_url = super::base_url();
    api::create_rtcp(base_url).await
}

/// Have WebRTC Gateway close a rtcp socket.
///
/// It's bindings for DELETE /media/rtcp/{rtcp_id}
///
/// [API](http://35.200.46.204/#/3.media/media_rtcp_delete)
///
/// # Examples
/// ```
/// use skyway_webrtc_gateway_api::media::delete_rtcp;
/// use skyway_webrtc_gateway_api::prelude::RtcpId;
///
/// async fn example() {
///     let rtcp_id = RtcpId::new("rc-example");
///     let result = delete_rtcp(&rtcp_id).await;
/// }
/// ```
pub async fn delete_rtcp(rtcp_id: &RtcpId) -> Result<(), error::Error> {
    let base_url = super::base_url();
    api::delete_rtcp(base_url, rtcp_id.as_str()).await
}

/// Have WebRTC Gateway start establishing MediaConnection to neighbour.
///
/// It's bindings for POST /media/connections.
///
/// [API](http://35.200.46.204/#/3.media/media_connection_create)
///
/// # Examples
/// ```
/// use skyway_webrtc_gateway_api::media::{call, CallQuery, Constraints};
/// use skyway_webrtc_gateway_api::prelude::{PeerId, MediaConnectionId, Token};
///
/// async fn example() {
///     let media_connection_id = MediaConnectionId::new("mc-example");
///     let query = CallQuery {
///         peer_id: PeerId::new("peer_id"),
///         token: Token::new("token"),
///         target_id: PeerId::new("target_id"),
///         constraints: Some(Constraints {
///             video: true,
///             videoReceiveEnabled: Some(false),
///             audio: false,
///             audioReceiveEnabled: Some(false),
///             video_params: None,
///             audio_params: None,
///         }),
///         redirect_params: None,
///     };
///     let result = call(&query).await;
/// }
/// ```
pub async fn call(call_params: &CallQuery) -> Result<CallResponse, error::Error> {
    let base_url = super::base_url();
    api::create_call(base_url, call_params).await
}

/// Have WebRTC Gateway accept to a request of establishing MediaConnection from neighbours.
///
/// It's bindings for POST /media/connections/{media_connection_id}/answer
///
/// [API](http://35.200.46.204/#/3.media/media_connection_answer)
///
/// # Examples
/// ```
/// use skyway_webrtc_gateway_api::media::{answer, AnswerQuery, Constraints};
/// use skyway_webrtc_gateway_api::prelude::MediaConnectionId;
///
/// async fn example() {
///     let media_connection_id = MediaConnectionId::new("mc-example");
///     let query = AnswerQuery {
///         constraints: Constraints {
///             video: true,
///             videoReceiveEnabled: Some(false),
///             audio: false,
///             audioReceiveEnabled: Some(false),
///             video_params: None,
///             audio_params: None,
///         },
///         redirect_params: None,
///     };
///     let result = answer(&media_connection_id, &query).await;
/// }
/// ```
pub async fn answer(
    media_connection_id: &MediaConnectionId,
    params: &AnswerQuery,
) -> Result<AnswerResponse, error::Error> {
    let base_url = super::base_url();
    api::answer(base_url, media_connection_id.as_str(), params).await
}

/// Have WebRTC Gateway close a MediaConnection
///
/// It's bindings for DELETE /media/connections/{media_connection_id}.
///
/// [API](http://35.200.46.204/#/3.media/media_connection_close)
///
/// # Examples
/// ```
/// use skyway_webrtc_gateway_api::media::disconnect;
/// use skyway_webrtc_gateway_api::prelude::MediaConnectionId;
///
/// async fn example() {
///     let media_connection_id = MediaConnectionId::new("mc-example");
///     let result = disconnect(&media_connection_id).await;
/// }
/// ```
pub async fn disconnect(media_connection_id: &MediaConnectionId) -> Result<(), error::Error> {
    let base_url = super::base_url();
    api::delete_call(base_url, media_connection_id.as_str()).await
}

/// Have WebRTC Gateway send a PLI(Picture Less Indication) packet
///
/// A PLI packets informs the encoder about the loss of an undefined amount of coded video data
/// belonging to one or more pictures([RFC](https://tools.ietf.org/html/rfc4585#section-6.3.1)).
///
/// It's bindings for POST /media/connections/{media_connection_id}/pli
///
/// [API](http://35.200.46.204/#/3.media/media_connection_pli)
///
/// # Examples
/// ```
/// use skyway_webrtc_gateway_api::media::send_pli;
/// use skyway_webrtc_gateway_api::prelude::{MediaConnectionId, PhantomId, SerializableSocket, SocketInfo};
///
/// async fn example() {
///     let media_connection_id = MediaConnectionId::new("mc-example");
///     let socket = SocketInfo::<PhantomId>::new(None, "127.0.0.1:8000".parse().unwrap());
///     let result = send_pli(&media_connection_id, &socket).await;
/// }
/// ```
pub async fn send_pli(
    media_connection_id: &MediaConnectionId,
    params: &SocketInfo<PhantomId>,
) -> Result<(), error::Error> {
    let base_url = super::base_url();
    api::pli(base_url, media_connection_id.as_str(), params).await
}

/// Request status of MediaConnection
///
/// This function keep listening events with GET /media/connections/{media_connection_id}/events
/// until it receives a CLOSE event or an Error event.
/// If it receives timeout, it ignores the event and listen events again.
///
/// [API](http://35.200.46.204/#/3.media/media_connection_event)
///
/// # Examples
/// ```
/// use futures::channel::mpsc;
/// use futures::future::{self, *};
/// use futures::stream::*;
/// use futures::*;
///
/// use skyway_webrtc_gateway_api::media::{MediaConnectionEventEnum, listen_events};
/// use skyway_webrtc_gateway_api::prelude::MediaConnectionId;
///
/// async fn example() {
///     let media_connection_id = MediaConnectionId::new("mc-example");
///     let (mc_event_notifier, mc_event_observer) = mpsc::channel::<MediaConnectionEventEnum>(0);
///     let mc_event_observer = mc_event_observer.for_each(|event| async move {
///     // Do something
///     });
///     let events_fut = listen_events(media_connection_id, mc_event_notifier);
///     let _ = join!(mc_event_observer, events_fut);
/// }
/// ```
pub async fn listen_events<'a>(
    media_connection_id: MediaConnectionId,
    mut event_notifier: mpsc::Sender<MediaConnectionEventEnum>,
) -> Result<(), error::Error> {
    let base_url = super::base_url();

    loop {
        let result = api::event(base_url, media_connection_id.as_str()).await?;
        match result {
            formats::EventEnum::READY => {
                if event_notifier
                    .send(MediaConnectionEventEnum::READY(media_connection_id.clone()))
                    .await
                    .is_err()
                {
                    return Err(error::Error::create_myerror("fail to notify an event"));
                };
            }
            formats::EventEnum::CLOSE => {
                if event_notifier
                    .send(MediaConnectionEventEnum::CLOSE(media_connection_id.clone()))
                    .await
                    .is_err()
                {
                    return Err(error::Error::create_myerror("fail to notify an event"));
                };
                break;
            }
            formats::EventEnum::STREAM => {
                if event_notifier
                    .send(MediaConnectionEventEnum::STREAM(
                        media_connection_id.clone(),
                    ))
                    .await
                    .is_err()
                {
                    return Err(error::Error::create_myerror("fail to notify an event"));
                };
            }
            formats::EventEnum::ERROR {
                error_message: message,
            } => {
                if event_notifier
                    .send(MediaConnectionEventEnum::ERROR((
                        media_connection_id.clone(),
                        message,
                    )))
                    .await
                    .is_err()
                {
                    return Err(error::Error::create_myerror("fail to notify an event"));
                };
            }
            formats::EventEnum::TIMEOUT => {}
        }
    }

    Ok(())
}

/// Request status of MediaConnection
///
/// It's bindings for GET /media/connections/{media_connection_id}/events.
///
/// [API](http://35.200.46.204/#/3.media/media_connection_status)
///
/// # Examples
/// ```
/// use skyway_webrtc_gateway_api::media::status;
/// use skyway_webrtc_gateway_api::prelude::MediaConnectionId;
///
/// async fn example() {
///     let media_connection_id = MediaConnectionId::new("mc-example");
///     let result = status(&media_connection_id).await;
/// }
/// ```
pub async fn status(
    media_connection_id: &MediaConnectionId,
) -> Result<MediaConnectionStatus, error::Error> {
    let base_url = super::base_url();
    api::status(base_url, media_connection_id.as_str()).await
}