palpo-core 0.0.2

Core library used by the palpo crates.
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
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
//! Common types for the [third party networks module][thirdparty].
//!
//! [thirdparty]: https://spec.matrix.org/latest/client-server-api/#third-party-networks

use std::collections::BTreeMap;

use salvo::prelude::*;
use serde::{Deserialize, Serialize};

use crate::{OwnedRoomAliasId, OwnedUserId, PrivOwnedStr, UnixMillis, serde::StringEnum};

/// Metadata about a third party protocol.
///
/// To create an instance of this type, first create a `ProtocolInit` and convert it via
/// `Protocol::from` / `.into()`.
#[derive(ToSchema, Deserialize, Serialize, Clone, Default, Debug)]
pub struct Protocol {
    /// Fields which may be used to identify a third party user.
    pub user_fields: Vec<String>,

    /// Fields which may be used to identify a third party location.
    pub location_fields: Vec<String>,

    /// A content URI representing an icon for the third party protocol.
    #[serde(default)]
    pub icon: String,

    /// The type definitions for the fields defined in `user_fields` and `location_fields`.
    pub field_types: BTreeMap<String, FieldType>,

    /// A list of objects representing independent instances of configuration.
    pub instances: Vec<ProtocolInstance>,
}

/// Initial set of fields of `Protocol`.
///
/// This struct will not be updated even if additional fields are added to `Prococol` in a new
/// (non-breaking) release of the Matrix specification.
#[derive(Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct ProtocolInit {
    /// Fields which may be used to identify a third party user.
    pub user_fields: Vec<String>,

    /// Fields which may be used to identify a third party location.
    pub location_fields: Vec<String>,

    /// A content URI representing an icon for the third party protocol.
    pub icon: String,

    /// The type definitions for the fields defined in `user_fields` and `location_fields`.
    pub field_types: BTreeMap<String, FieldType>,

    /// A list of objects representing independent instances of configuration.
    pub instances: Vec<ProtocolInstance>,
}

impl From<ProtocolInit> for Protocol {
    fn from(init: ProtocolInit) -> Self {
        let ProtocolInit {
            user_fields,
            location_fields,
            icon,
            field_types,
            instances,
        } = init;
        Self {
            user_fields,
            location_fields,
            icon,
            field_types,
            instances,
        }
    }
}

/// Metadata about an instance of a third party protocol.
///
/// To create an instance of this type, first create a `ProtocolInstanceInit` and convert it via
/// `ProtocolInstance::from` / `.into()`.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct ProtocolInstance {
    /// A human-readable description for the protocol, such as the name.
    pub desc: String,

    /// An optional content URI representing the protocol.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,

    /// Preset values for `fields` the client may use to search by.
    pub fields: BTreeMap<String, String>,

    /// A unique identifier across all instances.
    pub network_id: String,

    /// A unique identifier across all instances.
    ///
    /// See [matrix-spec#833](https://github.com/matrix-org/matrix-spec/issues/833).
    #[cfg(feature = "unstable-unspecified")]
    pub instance_id: String,
}

/// Initial set of fields of `Protocol`.
///
/// This struct will not be updated even if additional fields are added to `Prococol` in a new
/// (non-breaking) release of the Matrix specification.
#[derive(Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct ProtocolInstanceInit {
    /// A human-readable description for the protocol, such as the name.
    pub desc: String,

    /// Preset values for `fields` the client may use to search by.
    pub fields: BTreeMap<String, String>,

    /// A unique identifier across all instances.
    pub network_id: String,

    /// A unique identifier across all instances.
    ///
    /// See [matrix-spec#833](https://github.com/matrix-org/matrix-spec/issues/833).
    #[cfg(feature = "unstable-unspecified")]
    pub instance_id: String,
}

impl From<ProtocolInstanceInit> for ProtocolInstance {
    fn from(init: ProtocolInstanceInit) -> Self {
        let ProtocolInstanceInit {
            desc,
            fields,
            network_id,
            #[cfg(feature = "unstable-unspecified")]
            instance_id,
        } = init;
        Self {
            desc,
            icon: None,
            fields,
            network_id,
            #[cfg(feature = "unstable-unspecified")]
            instance_id,
        }
    }
}

/// A type definition for a field used to identify third party users or locations.
///
/// To create an instance of this type, first create a `FieldTypeInit` and convert it via
/// `FieldType::from` / `.into()`.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct FieldType {
    /// A regular expression for validation of a field's value.
    pub regexp: String,

    /// A placeholder serving as a valid example of the field value.
    pub placeholder: String,
}

/// Initial set of fields of `FieldType`.
///
/// This struct will not be updated even if additional fields are added to `FieldType` in a new
/// (non-breaking) release of the Matrix specification.
#[derive(Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct FieldTypeInit {
    /// A regular expression for validation of a field's value.
    pub regexp: String,

    /// A placeholder serving as a valid example of the field value.
    pub placeholder: String,
}

impl From<FieldTypeInit> for FieldType {
    fn from(init: FieldTypeInit) -> Self {
        let FieldTypeInit { regexp, placeholder } = init;
        Self { regexp, placeholder }
    }
}

/// A third party network location.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct Location {
    /// An alias for a matrix room.
    pub alias: OwnedRoomAliasId,

    /// The protocol ID that the third party location is a part of.
    pub protocol: String,

    /// Information used to identify this third party location.
    pub fields: BTreeMap<String, String>,
}

impl Location {
    /// Creates a new `Location` with the given alias, protocol and fields.
    pub fn new(alias: OwnedRoomAliasId, protocol: String, fields: BTreeMap<String, String>) -> Self {
        Self {
            alias,
            protocol,
            fields,
        }
    }
}

/// A third party network user.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct User {
    /// A matrix user ID representing a third party user.
    pub user_id: OwnedUserId,

    /// The protocol ID that the third party user is a part of.
    pub protocol: String,

    /// Information used to identify this third party user.
    pub fields: BTreeMap<String, String>,
}

impl User {
    /// Creates a new `User` with the given user_id, protocol and fields.
    pub fn new(user_id: OwnedUserId, protocol: String, fields: BTreeMap<String, String>) -> Self {
        Self {
            user_id,
            protocol,
            fields,
        }
    }
}

/// The medium of a third party identifier.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, PartialEq, Eq, StringEnum)]
#[palpo_enum(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Medium {
    /// Email address identifier
    Email,

    /// Phone number identifier
    Msisdn,

    #[doc(hidden)]
    #[salvo(schema(value_type = String))]
    _Custom(PrivOwnedStr),
}

/// An identifier external to Matrix.
///
/// To create an instance of this type, first create a `ThirdPartyIdentifierInit` and convert it to
/// this type using `ThirdPartyIdentifier::Init` / `.into()`.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct ThirdPartyIdentifier {
    /// The third party identifier address.
    pub address: String,

    /// The medium of third party identifier.
    pub medium: Medium,

    /// The time when the identifier was validated by the identity server.
    pub validated_at: UnixMillis,

    /// The time when the homeserver associated the third party identifier with the user.
    pub added_at: UnixMillis,
}

/// Initial set of fields of `ThirdPartyIdentifier`.
///
/// This struct will not be updated even if additional fields are added to `ThirdPartyIdentifier`
/// in a new (non-breaking) release of the Matrix specification.
#[derive(Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct ThirdPartyIdentifierInit {
    /// The third party identifier address.
    pub address: String,

    /// The medium of third party identifier.
    pub medium: Medium,

    /// The time when the identifier was validated by the identity server.
    pub validated_at: UnixMillis,

    /// The time when the homeserver associated the third party identifier with the user.
    pub added_at: UnixMillis,
}

impl From<ThirdPartyIdentifierInit> for ThirdPartyIdentifier {
    fn from(init: ThirdPartyIdentifierInit) -> Self {
        let ThirdPartyIdentifierInit {
            address,
            medium,
            validated_at,
            added_at,
        } = init;
        ThirdPartyIdentifier {
            address,
            medium,
            validated_at,
            added_at,
        }
    }
}

// `GET /_matrix/client/*/thirdparty/protocols`
//
// Fetches the overall metadata about protocols supported by the homeserver.
// `/v3/` ([spec])
//
// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3thirdpartyprotocols
// const METADATA: Metadata = metadata! {
//     method: GET,
//     rate_limited: false,
//     authentication: AccessToken,
//     history: {
//         1.0 => "/_matrix/client/r0/thirdparty/protocols",
//         1.1 => "/_matrix/client/v3/thirdparty/protocols",
//     }
// };

/// Response type for the `get_protocols` endpoint.

#[derive(ToSchema, Serialize, Default, Debug)]

pub struct ProtocolsResBody(
    /// Metadata about protocols supported by the homeserver.
    BTreeMap<String, Protocol>,
);

impl ProtocolsResBody {
    /// Creates a new `Response` with the given protocols.
    pub fn new(protocols: BTreeMap<String, Protocol>) -> Self {
        Self(protocols)
    }
}

// `GET /_matrix/client/*/thirdparty/protocol/{protocol}`
//
// Fetches the metadata from the homeserver about a particular third party protocol.
// `/v3/` ([spec])
//
// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3thirdpartyprotocolprotocol
// const METADATA: Metadata = metadata! {
//     method: GET,
//     rate_limited: false,
//     authentication: AccessToken,
//     history: {
//         1.0 => "/_matrix/client/r0/thirdparty/protocol/:protocol",
//         1.1 => "/_matrix/client/v3/thirdparty/protocol/:protocol",
//     }
// };

/// Request type for the `get_protocol` endpoint.
// pub struct ProtocolReqBody {
//     /// The name of the protocol.
//     #[salvo(parameter(parameter_in = Path))]
//     pub protocol: String,
// }

/// Response type for the `get_protocol` endpoint.
#[derive(ToSchema, Serialize, Clone, Default, Debug)]
pub struct ProtocolResBody(
    /// Metadata about the protocol.
    pub Protocol,
);
impl ProtocolResBody {
    /// Creates a new `Response` with the given protocol.
    pub fn new(protocol: Protocol) -> Self {
        Self(protocol)
    }
}

// `GET /_matrix/client/*/thirdparty/location/{protocol}`
//
// Fetches third party locations for a protocol.
// `/v3/` ([spec])
//
// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3thirdpartylocationprotocol
// const METADATA: Metadata = metadata! {
//     method: GET,
//     rate_limited: false,
//     authentication: AccessToken,
//     history: {
//         1.0 => "/_matrix/client/r0/thirdparty/location/:protocol",
//         1.1 => "/_matrix/client/v3/thirdparty/location/:protocol",
//     }
// };

/// Request type for the `get_location_for_protocol` endpoint.
// pub struct LocationForProtocolReqBody {
//     /// The protocol used to communicate to the third party network.
//     #[salvo(parameter(parameter_in = Path))]
//     pub protocol: String,

//     /// One or more custom fields to help identify the third party location.
//     // The specification is incorrect for this parameter. See [matrix-spec#560](https://github.com/matrix-org/matrix-spec/issues/560).
//
//     pub fields: BTreeMap<String, String>,
// }

/// Response type for the `get_location_for_protocol` endpoint.
#[derive(ToSchema, Serialize, Default, Debug)]
pub struct LocationsResBody(
    /// List of matched third party locations.
    pub Vec<Location>,
);

impl LocationsResBody {
    /// Creates a new `Response` with the given locations.
    pub fn new(locations: Vec<Location>) -> Self {
        Self(locations)
    }
}

// `GET /_matrix/client/*/thirdparty/location`
//
// Retrieve an array of third party network locations from a Matrix room alias.
// `/v3/` ([spec])
//
// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3thirdpartylocation
// const METADATA: Metadata = metadata! {
//     method: GET,
//     rate_limited: false,
//     authentication: AccessToken,
//     history: {
//         1.0 => "/_matrix/client/r0/thirdparty/location",
//         1.1 => "/_matrix/client/v3/thirdparty/location",
//     }
// };

/// Request type for the `get_location_for_room_alias` endpoint.

// pub struct LocationReqBody {
//     /// The Matrix room alias to look up.
//     #[salvo(parameter(parameter_in = Query))]
//     pub alias: OwnedRoomAliasId,
// }

/// Response type for the `get_location_for_room_alias` endpoint.
// #[derive(ToSchema, Serialize, Debug)]
//
// pub struct LocationResBody {
//     /// List of matched third party locations.
//     pub locations: Vec<Location>,
// }
//
// impl LocationResBody {
//     /// Creates a new `Response` with the given locations.
//     pub fn new(locations: Vec<Location>) -> Self {
//         Self { locations }
//     }
// }

/// `GET /_matrix/client/*/thirdparty/user/{protocol}`
///
/// Fetches third party users for a protocol.
/// `/v3/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3thirdpartyuserprotocol
/// const METADATA: Metadata = metadata! {
///     method: GET,
///     rate_limited: false,
///     authentication: AccessToken,
///     history: {
///         1.0 => "/_matrix/client/r0/thirdparty/user/:protocol",
///         1.1 => "/_matrix/client/v3/thirdparty/user/:protocol",
///     }
/// };

/// Request type for the `get_user_for_protocol` endpoint.

// pub struct UserForProtocolReqBody {
//     /// The protocol used to communicate to the third party network.
//     #[salvo(parameter(parameter_in = Path))]
//     pub protocol: String,

//     /// One or more custom fields that are passed to the AS to help identify the user.
//     // The specification is incorrect for this parameter. See [matrix-spec#560](https://github.com/matrix-org/matrix-spec/issues/560).
//
//     pub fields: BTreeMap<String, String>,
// }

/// `GET /_matrix/client/*/thirdparty/user`
///
/// Retrieve an array of third party users from a Matrix User ID.
/// `/v3/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3thirdpartyuser
/// const METADATA: Metadata = metadata! {
///     method: GET,
///     rate_limited: false,
///     authentication: AccessToken,
///     history: {
///         1.0 => "/_matrix/client/r0/thirdparty/user",
///         1.1 => "/_matrix/client/v3/thirdparty/user",
///     }
/// };
///
/// Response type for the `get_user_for_protocol` endpoint.
#[derive(ToSchema, Serialize, Default, Debug)]
pub struct UsersResBody(
    /// List of matched third party users.
    pub Vec<User>,
);

impl UsersResBody {
    /// Creates a new `Response` with the given users.
    pub fn new(users: Vec<User>) -> Self {
        Self(users)
    }
}

#[cfg(test)]
mod tests {
    use serde_json::{from_value as from_json_value, json, to_value as to_json_value};

    use super::{Medium, ThirdPartyIdentifier};
    use crate::UnixMillis;

    #[test]
    fn third_party_identifier_serde() {
        let third_party_id = ThirdPartyIdentifier {
            address: "monkey@banana.island".into(),
            medium: Medium::Email,
            validated_at: UnixMillis(1_535_176_800_000_u64.try_into().unwrap()),
            added_at: UnixMillis(1_535_336_848_756_u64.try_into().unwrap()),
        };

        let third_party_id_serialized = json!({
            "medium": "email",
            "address": "monkey@banana.island",
            "validated_at": 1_535_176_800_000_u64,
            "added_at": 1_535_336_848_756_u64
        });

        assert_eq!(
            to_json_value(third_party_id.clone()).unwrap(),
            third_party_id_serialized
        );
        assert_eq!(third_party_id, from_json_value(third_party_id_serialized).unwrap());
    }
}