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
//! [`Member`] definitions.

use std::{collections::HashMap, fmt, str::FromStr, time::Duration};

use derive_more::{AsRef, Display, Error, From, FromStr, Into};
use ref_cast::RefCast;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use url::Url;

use super::{endpoint, room, Pipeline};

/// Media [`Element`] representing a client authorized to participate in some
/// bigger media pipeline ([`Room`], for example).
///
/// [`Element`]: crate::Element
/// [`Room`]: crate::Room
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Member {
    /// ID of this [`Member`] media [`Element`].
    ///
    /// [`Element`]: crate::Element
    pub id: Id,

    /// [`Spec`] of this [`Member`] media [`Element`].
    ///
    /// [`Element`]: crate::Element
    pub spec: Spec,
}

/// Spec of a [`Member`] media [`Element`].
///
/// [`Element`]: crate::Element
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Spec {
    /// Media [`Pipeline`] representing this [`Member`] media [`Element`].
    ///
    /// [`Element`]: crate::Element
    pub pipeline: Pipeline<endpoint::Id, endpoint::Spec>,

    /// [`Credentials`] to authenticate this [`Member`] in [Client API] with.
    ///
    /// [`None`] if no authentication is required.
    ///
    /// [Client API]: https://tinyurl.com/266y74tf
    pub credentials: Option<Credentials>,

    /// [`Url`] of the callback to fire when this [`Member`] establishes a
    /// persistent connection with a media server via [Client API].
    ///
    /// [Client API]: https://tinyurl.com/266y74tf
    pub on_join: Option<Url>,

    /// [`Url`] of the callback to fire when this [`Member`] finishes a
    /// persistent connection with a media server via [Client API].
    ///
    /// [Client API]: https://tinyurl.com/266y74tf
    pub on_leave: Option<Url>,

    /// Timeout of receiving heartbeat messages from this [`Member`] via
    /// [Client API].
    ///
    /// Once reached, this [`Member`] is considered being idle.
    ///
    /// [Client API]: https://tinyurl.com/266y74tf
    #[cfg_attr(feature = "serde", serde(default, with = "humantime_serde"))]
    pub idle_timeout: Option<Duration>,

    /// Timeout of reconnecting for this [`Member`] via [Client API].
    ///
    /// Once reached, this [`Member`] is considered disconnected.
    ///
    /// [Client API]: https://tinyurl.com/266y74tf
    #[cfg_attr(feature = "serde", serde(default, with = "humantime_serde"))]
    pub reconnect_timeout: Option<Duration>,

    /// Interval of pinging with heartbeat messages this [`Member`] via
    /// [Client API] by a media server.
    ///
    /// If [`None`] then the default interval of a media server is used, if
    /// configured.
    ///
    /// [Client API]: https://tinyurl.com/266y74tf
    #[cfg_attr(feature = "serde", serde(default, with = "humantime_serde"))]
    pub ping_interval: Option<Duration>,
}

/// ID of a [`Member`] media [`Element`].
///
/// [`Element`]: crate::Element
#[derive(
    AsRef,
    Clone,
    Debug,
    Display,
    Eq,
    From,
    Hash,
    Into,
    Ord,
    PartialEq,
    PartialOrd,
    RefCast,
)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[from(types("&str", String))]
#[into(owned(types(String)))]
#[repr(transparent)]
pub struct Id(Box<str>);

#[cfg(feature = "client-api")]
impl From<medea_client_api_proto::MemberId> for Id {
    fn from(id: medea_client_api_proto::MemberId) -> Self {
        id.0.into()
    }
}

/// [URI] used by a [`Member`] to connect to a media server via [Client API].
///
/// [Client API]: https://tinyurl.com/266y74tf
/// [URI]: https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
#[derive(Clone, Debug)]
pub struct Sid {
    /// Public [URL] to establish [WebSocket] connections with.
    ///
    /// [URL]: https://en.wikipedia.org/wiki/URL
    /// [WebSocket]: https://en.wikipedia.org/wiki/WebSocket
    pub public_url: PublicUrl,

    /// ID of the [`Room`] the [`Member`] participates in.
    ///
    /// [`Room`]: room::Room
    pub room_id: room::Id,

    /// ID of the [`Member`] who establishes [WebSocket] connections.
    ///
    /// [WebSocket]: https://en.wikipedia.org/wiki/WebSocket
    pub member_id: Id,

    /// [`PlainCredentials`] of the [`Member`] to authenticate him with.
    pub creds: Option<PlainCredentials>,
}

impl fmt::Display for Sid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}/{}", self.public_url, self.room_id, self.member_id)?;
        if let Some(plain) = &self.creds {
            write!(f, "?token={plain}")?;
        }
        Ok(())
    }
}

impl FromStr for Sid {
    type Err = ParseSidError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut url = Url::parse(s)
            .map_err(|e| ParseSidError::InvalidUrl(s.into(), e))?;

        let creds = url.query_pairs().find_map(|(k, v)| {
            (k.as_ref() == "token").then(|| v.as_ref().into())
        });

        url.set_fragment(None);
        url.set_query(None);

        let err_missing = || ParseSidError::MissingPaths(s.into());
        let mut segments = url.path_segments().ok_or_else(err_missing)?.rev();
        let member_id = segments.next().ok_or_else(err_missing)?.into();
        let room_id = segments.next().ok_or_else(err_missing)?.into();

        // Removes last two segments.
        if let Ok(mut path) = url.path_segments_mut() {
            _ = path.pop().pop();
        }

        Ok(Self {
            public_url: url.into(),
            room_id,
            member_id,
            creds,
        })
    }
}

/// Possible errors of parsing a [`Sid`].
#[derive(Debug, Display, Error)]
pub enum ParseSidError {
    /// Some paths are missing in the provided [URI].
    ///
    /// `ws://localhost:8080/ws//qwerty`, for example.
    ///
    /// [URI]: https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
    #[display(fmt = "Missing paths in URI: {}", _0)]
    MissingPaths(#[error(not(source))] Box<str>),

    /// Error of parsing the provided [URI].
    ///
    /// [URI]: https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
    #[display(fmt = "Cannot parse provided URI `{}`: {}", _0, _1)]
    InvalidUrl(Box<str>, #[error(source)] url::ParseError),
}

/// Collection of [`Sid`]s to be used by [`Member`]s to connect to a media
/// server via [Client API].
///
/// [Client API]: https://tinyurl.com/266y74tf
pub type Sids = HashMap<Id, Sid>;

/// Public [URL] of HTTP server exposing [Client API]. It's assumed that HTTP
/// server can be reached via this [URL] externally.
///
/// This address is returned from [`ControlApi`] in a [`Sid`] and a client side
/// should use this address to start its session.
///
/// [`ControlApi`]: crate::ControlApi
/// [Client API]: https://tinyurl.com/266y74tf
/// [URL]: https://en.wikipedia.org/wiki/URL
#[derive(
    AsRef,
    Clone,
    Debug,
    Display,
    Eq,
    From,
    FromStr,
    Hash,
    Into,
    Ord,
    PartialEq,
    PartialOrd,
)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct PublicUrl(Url);

/// Credentials of a [`Member`] media [`Element`] for its client side to
/// authorize via [Client API] with.
///
/// [`Element`]: crate::Element
/// [Client API]: https://tinyurl.com/266y74tf
#[derive(Clone, Debug, Eq, From, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum Credentials {
    /// [Argon2] hash of credentials.
    ///
    /// [`Sid`] won't contain a `token` query parameter if
    /// [`Credentials::Hash`] is used, so it should be appended manually on
    /// a client side.
    ///
    /// [Argon2]: https://en.wikipedia.org/wiki/Argon2
    #[from(ignore)]
    Hash(Box<str>),

    /// Plain text credentials.
    Plain(PlainCredentials),
}

impl Credentials {
    /// Generates new random [`Credentials::Plain`].
    #[must_use]
    pub fn random() -> Self {
        use rand::{distributions::Alphanumeric, Rng as _};

        Self::Plain(
            rand::thread_rng()
                .sample_iter(&Alphanumeric)
                .take(32)
                .map(char::from)
                .collect::<String>()
                .into(),
        )
    }
}

/// Plain [`Credentials`] returned in a [`Sid`].
#[derive(
    AsRef,
    Clone,
    Debug,
    Display,
    Eq,
    From,
    Hash,
    Into,
    Ord,
    PartialEq,
    PartialOrd,
)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[from(types("&str", String))]
#[into(owned(types(String)))]
pub struct PlainCredentials(Box<str>); // TODO: Use `secrecy` crate.