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
//! Room membership endpoints.

use itertools::Itertools;
use reqwest::Url;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};

use crate::events::{AnyStrippedStateEvent, StateEventType, room::member::RoomMemberEventContent};
use crate::identifiers::*;
use crate::sending::{SendRequest, SendResult};
use crate::{RawJsonValue, UnixMillis, serde::RawJson};

pub fn invite_user_request_v2(
    origin: &str,
    args: InviteUserReqArgs,
    body: InviteUserReqBodyV2,
) -> SendResult<SendRequest> {
    let url = Url::parse(&format!(
        "{origin}/_matrix/federation/v2/invite/{}/{}",
        args.room_id, args.event_id
    ))?;
    crate::sending::put(url).stuff(body)
}
#[derive(ToParameters, Deserialize, Debug)]
pub struct InviteUserReqArgs {
    /// The room ID that is about to be joined.
    ///
    /// Do not use this. Instead, use the `room_id` field inside the PDU.
    #[salvo(parameter(parameter_in = Path))]
    pub room_id: OwnedRoomId,

    /// The event ID for the join event.
    #[salvo(parameter(parameter_in = Path))]
    pub event_id: OwnedEventId,
}

#[derive(ToSchema, Deserialize, Serialize, Debug)]
pub struct InviteUserReqBodyV2 {
    // /// The room ID that the user is being invited to.
    // #[salvo(parameter(parameter_in = Path))]
    // pub room_id: OwnedRoomId,

    // /// The event ID for the invite event, generated by the inviting server.
    // #[salvo(parameter(parameter_in = Path))]
    // pub event_id: OwnedEventId,
    /// The version of the room where the user is being invited to.
    pub room_version: RoomVersionId,

    /// The invite event which needs to be signed.
    #[salvo(schema(value_type = Object, additional_properties = true))]
    pub event: Box<RawJsonValue>,

    /// An optional list of simplified events to help the receiver of the invite identify the room.
    pub invite_room_state: Vec<RawJson<AnyStrippedStateEvent>>,

    /// An optional list of servers the invited homeserver should attempt to join or leave via,
    /// according to [MSC4125](https://github.com/matrix-org/matrix-spec-proposals/pull/4125).
    ///
    /// If present, it must not be empty.
    #[serde(skip_serializing_if = "Option::is_none", rename = "org.matrix.msc4125.via")]
    pub via: Option<Vec<OwnedServerName>>,
}
crate::json_body_modifier!(InviteUserReqBodyV2);

#[derive(ToSchema, Deserialize, Debug)]
pub struct InviteUserReqBodyV1 {
    /// The matrix ID of the user who sent the original `m.room.third_party_invite`.
    pub sender: OwnedUserId,

    /// The name of the inviting homeserver.
    pub origin: OwnedServerName,

    /// A timestamp added by the inviting homeserver.
    pub origin_server_ts: UnixMillis,

    /// The value `m.room.member`.
    #[serde(rename = "type")]
    pub kind: StateEventType,

    /// The user ID of the invited member.
    pub state_key: OwnedUserId,

    /// The content of the event.
    pub content: RoomMemberEventContent,

    /// Information included alongside the event that is not signed.
    #[serde(default, skip_serializing_if = "UnsignedEventContent::is_empty")]
    pub unsigned: UnsignedEventContentV1,
}

#[derive(ToSchema, Serialize, Deserialize, Debug)]
pub struct InviteUserResBodyV2 {
    /// The signed invite event.
    #[salvo(schema(value_type = Object))]
    pub event: Box<RawJsonValue>,
}

#[derive(ToSchema, Serialize, Debug)]
pub struct InviteUserResBodyV1 {
    /// The signed invite event.
    #[serde(with = "crate::federation::serde::v1_pdu")]
    #[salvo(schema(value_type = Object))]
    pub event: Box<RawJsonValue>,
}

#[derive(ToSchema, Deserialize, Serialize, Debug)]
#[salvo(schema(value_type = Object))]
pub struct SendJoinReqBody(
    /// The invite event which needs to be signed.
    pub Box<RawJsonValue>,
);
crate::json_body_modifier!(SendJoinReqBody);

#[derive(ToSchema, Deserialize, Serialize, Debug)]
pub struct SendJoinResBodyV2(
    /// The signed invite event.
    pub RoomStateV2,
);

#[derive(ToSchema, Serialize, Debug)]
pub struct SendJoinResBodyV1(
    /// Full state of the room.
    pub RoomStateV1,
);

impl SendJoinResBodyV1 {
    /// Creates a new `Response` with the given room state.
    pub fn new(room_state: RoomStateV1) -> Self {
        Self(room_state)
    }
}

/// Full state of the room.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct RoomStateV2 {
    /// Whether `m.room.member` events have been omitted from `state`.
    ///
    /// Defaults to `false`.
    #[serde(default, skip_serializing_if = "crate::serde::is_default")]
    pub members_omitted: bool,

    /// The full set of authorization events that make up the state of the room,
    /// and their authorization events, recursively.
    ///
    /// If the request had `omit_members` set to `true`, then any events that are returned in
    /// `state` may be omitted from `auth_chain`, whether or not membership events are omitted
    /// from `state`.
    #[salvo(schema(value_type = Vec<Object>))]
    pub auth_chain: Vec<Box<RawJsonValue>>,

    /// The room state.
    ///
    /// If the request had `omit_members` set to `true`, events of type `m.room.member` may be
    /// omitted from the response to reduce the size of the response. If this is done,
    /// `members_omitted` must be set to `true`.
    #[salvo(schema(value_type = Object))]
    pub state: Vec<Box<RawJsonValue>>,

    /// The signed copy of the membership event sent to other servers by the
    /// resident server, including the resident server's signature.
    ///
    /// Required if the room version supports restricted join rules.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[salvo(schema(value_type = Object))]
    pub event: Option<Box<RawJsonValue>>,

    /// A list of the servers active in the room (ie, those with joined members) before the join.
    ///
    /// Required if `members_omitted` is set to `true`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub servers_in_room: Option<Vec<String>>,
}

impl RoomStateV2 {
    /// Creates an empty `RoomState` with the given `origin`.
    ///
    /// With the `unstable-unspecified` feature, this method doesn't take any parameters.
    /// See [matrix-spec#374](https://github.com/matrix-org/matrix-spec/issues/374).
    pub fn new() -> Self {
        Self {
            auth_chain: Vec::new(),
            state: Vec::new(),
            event: None,
            members_omitted: false,
            servers_in_room: None,
        }
    }
}

/// Full state of the room.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct RoomStateV1 {
    /// The full set of authorization events that make up the state of the room,
    /// and their authorization events, recursively.
    #[salvo(schema(value_type = Vec<Object>))]
    pub auth_chain: Vec<Box<RawJsonValue>>,

    /// The room state.
    #[salvo(schema(value_type = Vec<Object>))]
    pub state: Vec<Box<RawJsonValue>>,

    /// The signed copy of the membership event sent to other servers by the
    /// resident server, including the resident server's signature.
    ///
    /// Required if the room version supports restricted join rules.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[salvo(schema(value_type = Vec<Object>))]
    pub event: Option<Box<RawJsonValue>>,
}
impl RoomStateV1 {
    /// Creates an empty `RoomState` with the given `origin`.
    ///
    /// With the `unstable-unspecified` feature, this method doesn't take any parameters.
    /// See [matrix-spec#374](https://github.com/matrix-org/matrix-spec/issues/374).
    pub fn new() -> Self {
        Self {
            auth_chain: Vec::new(),
            state: Vec::new(),
            event: None,
        }
    }
}

/// Information included alongside an event that is not signed.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
pub struct UnsignedEventContentV1 {
    /// An optional list of simplified events to help the receiver of the invite identify the room.
    /// The recommended events to include are the join rules, canonical alias, avatar, and name of
    /// the room.
    #[serde(skip_serializing_if = "<[_]>::is_empty")]
    #[salvo(schema(value_type = Vec<Object>))]
    pub invite_room_state: Vec<RawJson<AnyStrippedStateEvent>>,
}

impl UnsignedEventContentV1 {
    /// Creates an empty `UnsignedEventContent`.
    pub fn new() -> Self {
        Default::default()
    }

    /// Checks whether all of the fields are empty.
    pub fn is_empty(&self) -> bool {
        self.invite_room_state.is_empty()
    }
}

// const METADATA: Metadata = metadata! {
//     method: GET,
//     rate_limited: false,
//     authentication: ServerSignatures,
//     history: {
//         1.0 => "/_matrix/federation/v1/make_leave/:room_id/:user_id",
//     }
// };

pub fn make_leave_request(origin: &str, room_id: &RoomId, user_id: &UserId) -> SendResult<SendRequest> {
    let url = Url::parse(&format!(
        "{origin}/_matrix/federation/v1/make_leave/{room_id}/{user_id}"
    ))?;
    Ok(crate::sending::get(url))
}
#[derive(ToParameters, Deserialize, Debug)]
pub struct MakeLeaveReqArgs {
    /// Room in which the event to be reported is located.
    #[salvo(parameter(parameter_in = Path))]
    pub room_id: OwnedRoomId,

    /// Event to report.
    #[salvo(parameter(parameter_in = Path))]
    pub user_id: OwnedUserId,
}

/// Response type for the `get_leave_event` endpoint.
#[derive(ToSchema, Serialize, Deserialize, Debug)]

pub struct MakeLeaveResBody {
    /// The version of the room where the server is trying to leave.
    ///
    /// If not provided, the room version is assumed to be either "1" or "2".
    pub room_version: Option<RoomVersionId>,

    /// An unsigned template event.
    ///
    /// Note that events have a different format depending on the room version - check the room
    /// version specification for precise event formats.
    #[salvo(schema(value_type = Object, additional_properties = true))]
    pub event: Box<RawJsonValue>,
}
impl MakeLeaveResBody {
    /// Creates a new `Response` with:
    /// * the version of the room where the server is trying to leave.
    /// * an unsigned template event.
    pub fn new(room_version: Option<RoomVersionId>, event: Box<RawJsonValue>) -> Self {
        Self { room_version, event }
    }
}

// const METADATA: Metadata = metadata! {
//     method: PUT,
//     rate_limited: false,
//     authentication: ServerSignatures,
//     history: {
//         1.0 => "/_matrix/federation/v2/send_leave/:room_id/:event_id",
//     }
// };

pub fn send_leave_request_v2(
    origin: &str,
    args: SendLeaveReqArgsV2,
    body: SendLeaveReqBody,
) -> SendResult<SendRequest> {
    let url = Url::parse(&format!(
        "{origin}/_matrix/federation/v2/send_leave/{}/{}",
        args.room_id, args.event_id
    ))?;
    crate::sending::put(url).stuff(body)
}
#[derive(ToParameters, Deserialize, Serialize, Debug)]
pub struct SendLeaveReqArgsV2 {
    /// The room ID that is about to be left.
    ///
    /// Do not use this. Instead, use the `room_id` field inside the PDU.
    #[salvo(parameter(parameter_in = Path))]
    pub room_id: OwnedRoomId,

    /// The event ID for the leave event.
    #[salvo(parameter(parameter_in = Path))]
    pub event_id: OwnedEventId,
}
/// Request type for the `create_leave_event` endpoint.
#[derive(ToSchema, Deserialize, Serialize, Debug)]
#[salvo(schema(value_type = Object))]
pub struct SendLeaveReqBody(
    /// The PDU.
    pub Box<RawJsonValue>,
);
crate::json_body_modifier!(SendLeaveReqBody);

/// `PUT /_matrix/federation/*/send_join/{room_id}/{event_id}`
///
/// Send a join event to a resident server.

// const METADATA: Metadata = metadata! {
//     method: PUT,
//     rate_limited: false,
//     authentication: ServerSignatures,
//     history: {
//         1.0 => "/_matrix/federation/v2/send_join/:room_id/:event_id",
//     }
// };

pub fn send_join_request(origin: &str, args: SendJoinArgs, body: SendJoinReqBody) -> SendResult<SendRequest> {
    let url = Url::parse(&format!(
        "{origin}/_matrix/federation/v2/send_join/{}/{}?omit_members={}",
        &args.room_id, &args.event_id, args.omit_members
    ))?;
    crate::sending::put(url).stuff(body)
}
/// Request type for the `create_join_event` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct SendJoinArgs {
    /// The room ID that is about to be joined.
    ///
    /// Do not use this. Instead, use the `room_id` field inside the PDU.
    #[salvo(parameter(parameter_in = Path))]
    pub room_id: OwnedRoomId,

    /// The event ID for the join event.
    #[salvo(parameter(parameter_in = Path))]
    pub event_id: OwnedEventId,

    /// Indicates whether the calling server can accept a reduced response.
    ///
    /// If `true`, membership events are omitted from `state` and redundant events are omitted from
    /// `auth_chain` in the response.
    ///
    /// If the room to be joined has no `m.room.name` nor `m.room.canonical_alias` events in its
    /// current state, the resident server should determine the room members who would be
    /// included in the `m.heroes` property of the room summary as defined in the [Client-Server
    /// `/sync` response]. The resident server should include these members' membership events in
    /// the response `state` field, and include the auth chains for these membership events in
    /// the response `auth_chain` field.
    ///
    /// [Client-Server `/sync` response]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3sync
    #[salvo(parameter(parameter_in = Query))]
    #[serde(default, skip_serializing_if = "crate::serde::is_default")]
    pub omit_members: bool,
}

// const METADATA: Metadata = metadata! {
//     method: GET,
//     rate_limited: false,
//     authentication: ServerSignatures,
//     history: {
//         1.0 => "/_matrix/federation/v1/make_join/:room_id/:user_id",
//     }
// };

pub fn make_join_request(origin: &str, args: MakeJoinReqArgs) -> SendResult<SendRequest> {
    let ver = args.ver.iter().map(|v| format!("ver={v}")).join("&");
    let ver = if ver.is_empty() { "" } else { &*format!("?{}", ver) };

    let url = Url::parse(&format!(
        "{origin}/_matrix/federation/v1/make_join/{}/{}{}",
        args.room_id, args.user_id, ver
    ))?;
    Ok(crate::sending::get(url))
}

/// Request type for the `create_join_event_template` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct MakeJoinReqArgs {
    /// The room ID that is about to be joined.
    #[salvo(parameter(parameter_in = Path))]
    pub room_id: OwnedRoomId,

    /// The user ID the join event will be for.
    #[salvo(parameter(parameter_in = Path))]
    pub user_id: OwnedUserId,

    /// The room versions the sending server has support for.
    ///
    /// Defaults to `&[RoomVersionId::V1]`.
    #[salvo(parameter(parameter_in = Query))]
    #[serde(default = "default_ver", skip_serializing_if = "is_default_ver")]
    pub ver: Vec<RoomVersionId>,
}

/// Response type for the `create_join_event_template` endpoint.
#[derive(ToSchema, Serialize, Deserialize, Debug)]

pub struct MakeJoinResBody {
    /// The version of the room where the server is trying to join.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub room_version: Option<RoomVersionId>,

    /// An unsigned template event.
    #[salvo(schema(value_type = Object, additional_properties = true))]
    pub event: Box<RawJsonValue>,
}

impl MakeJoinResBody {
    /// Creates a new `Response` with the given template event.
    pub fn new(event: Box<RawJsonValue>) -> Self {
        Self {
            room_version: None,
            event,
        }
    }
}

fn default_ver() -> Vec<RoomVersionId> {
    vec![RoomVersionId::V1]
}

fn is_default_ver(ver: &[RoomVersionId]) -> bool {
    *ver == [RoomVersionId::V1]
}