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
use std::{collections::HashMap, panic};
use http::Response;
pub use matrix_sdk_test_macros::async_test;
use ruma::{
    api::{client::r0::sync::sync_events::Response as SyncResponse, IncomingResponse},
    events::{
        presence::PresenceEvent, AnyGlobalAccountDataEvent, AnySyncEphemeralRoomEvent,
        AnySyncRoomEvent, AnySyncStateEvent,
    },
    room_id, RoomId,
};
use serde_json::Value as JsonValue;
#[cfg(feature = "appservice")]
pub mod appservice;
pub mod test_json;
#[derive(Debug)]
pub enum EventsJson {
    Alias,
    Aliases,
    Create,
    FullyRead,
    HistoryVisibility,
    JoinRules,
    Member,
    MemberNameChange,
    MessageEmote,
    MessageNotice,
    MessageText,
    Name,
    PowerLevels,
    Presence,
    RedactedInvalid,
    RedactedState,
    Redacted,
    Redaction,
    RoomAvatar,
    Tag,
    Topic,
    Typing,
}
#[derive(Default)]
pub struct EventBuilder {
    
    joined_room_events: HashMap<RoomId, Vec<AnySyncRoomEvent>>,
    
    invited_room_events: HashMap<RoomId, Vec<AnySyncStateEvent>>,
    
    left_room_events: HashMap<RoomId, Vec<AnySyncRoomEvent>>,
    
    presence_events: Vec<PresenceEvent>,
    
    state_events: Vec<AnySyncStateEvent>,
    
    ephemeral: Vec<AnySyncEphemeralRoomEvent>,
    
    account_data: Vec<AnyGlobalAccountDataEvent>,
    
    
    batch_counter: i64,
}
impl EventBuilder {
    pub fn new() -> Self {
        let builder: EventBuilder = Default::default();
        builder
    }
    
    pub fn add_ephemeral(&mut self, json: EventsJson) -> &mut Self {
        let val: &JsonValue = match json {
            EventsJson::Typing => &test_json::TYPING,
            _ => panic!("unknown ephemeral event {:?}", json),
        };
        let event = serde_json::from_value::<AnySyncEphemeralRoomEvent>(val.clone()).unwrap();
        self.ephemeral.push(event);
        self
    }
    
    #[allow(clippy::match_single_binding, unused)]
    pub fn add_account(&mut self, json: EventsJson) -> &mut Self {
        let val: &JsonValue = match json {
            _ => panic!("unknown account event {:?}", json),
        };
        let event = serde_json::from_value::<AnyGlobalAccountDataEvent>(val.clone()).unwrap();
        self.account_data.push(event);
        self
    }
    
    pub fn add_room_event(&mut self, json: EventsJson) -> &mut Self {
        let val: &JsonValue = match json {
            EventsJson::Member => &test_json::MEMBER,
            EventsJson::MemberNameChange => &test_json::MEMBER_NAME_CHANGE,
            EventsJson::PowerLevels => &test_json::POWER_LEVELS,
            _ => panic!("unknown room event json {:?}", json),
        };
        let event = serde_json::from_value::<AnySyncRoomEvent>(val.clone()).unwrap();
        self.add_joined_event(&room_id!("!SVkFJHzfwvuaIEawgC:localhost"), event);
        self
    }
    pub fn add_custom_joined_event(
        &mut self,
        room_id: &RoomId,
        event: serde_json::Value,
    ) -> &mut Self {
        let event = serde_json::from_value::<AnySyncRoomEvent>(event).unwrap();
        self.add_joined_event(room_id, event);
        self
    }
    fn add_joined_event(&mut self, room_id: &RoomId, event: AnySyncRoomEvent) {
        self.joined_room_events.entry(room_id.clone()).or_insert_with(Vec::new).push(event);
    }
    pub fn add_custom_invited_event(
        &mut self,
        room_id: &RoomId,
        event: serde_json::Value,
    ) -> &mut Self {
        let event = serde_json::from_value::<AnySyncStateEvent>(event).unwrap();
        self.invited_room_events.entry(room_id.clone()).or_insert_with(Vec::new).push(event);
        self
    }
    pub fn add_custom_left_event(
        &mut self,
        room_id: &RoomId,
        event: serde_json::Value,
    ) -> &mut Self {
        let event = serde_json::from_value::<AnySyncRoomEvent>(event).unwrap();
        self.left_room_events.entry(room_id.clone()).or_insert_with(Vec::new).push(event);
        self
    }
    
    pub fn add_state_event(&mut self, json: EventsJson) -> &mut Self {
        let val: &JsonValue = match json {
            EventsJson::Alias => &test_json::ALIAS,
            EventsJson::Aliases => &test_json::ALIASES,
            EventsJson::Name => &test_json::NAME,
            EventsJson::Member => &test_json::MEMBER,
            EventsJson::PowerLevels => &test_json::POWER_LEVELS,
            _ => panic!("unknown state event {:?}", json),
        };
        let event = serde_json::from_value::<AnySyncStateEvent>(val.clone()).unwrap();
        self.state_events.push(event);
        self
    }
    
    pub fn add_presence_event(&mut self, json: EventsJson) -> &mut Self {
        let val: &JsonValue = match json {
            EventsJson::Presence => &test_json::PRESENCE,
            _ => panic!("unknown presence event {:?}", json),
        };
        let event = serde_json::from_value::<PresenceEvent>(val.clone()).unwrap();
        self.presence_events.push(event);
        self
    }
    
    
    
    
    
    
    
    
    
    
    pub fn build_json_sync_response(&mut self) -> JsonValue {
        let main_room_id = room_id!("!SVkFJHzfwvuaIEawgC:localhost");
        
        
        let prev_batch = self.generate_sync_token();
        self.batch_counter += 1;
        let next_batch = self.generate_sync_token();
        
        let joined_room = serde_json::json!({
            "summary": {},
            "account_data": {
                "events": self.account_data
            },
            "ephemeral": {
                "events": self.ephemeral
            },
            "state": {
                "events": self.state_events
            },
            "timeline": {
                "events": self.joined_room_events.remove(&main_room_id).unwrap_or_default(),
                "limited": true,
                "prev_batch": prev_batch
            },
            "unread_notifications": {
                "highlight_count": 0,
                "notification_count": 11
            }
        });
        let mut joined_rooms: HashMap<RoomId, serde_json::Value> = HashMap::new();
        joined_rooms.insert(main_room_id, joined_room);
        for (room_id, events) in self.joined_room_events.drain() {
            let joined_room = serde_json::json!({
                "summary": {},
                "account_data": {
                    "events": [],
                },
                "ephemeral": {
                    "events": [],
                },
                "state": {
                    "events": [],
                },
                "timeline": {
                    "events": events,
                    "limited": true,
                    "prev_batch": prev_batch
                },
                "unread_notifications": {
                    "highlight_count": 0,
                    "notification_count": 11
                }
            });
            joined_rooms.insert(room_id, joined_room);
        }
        let mut left_rooms: HashMap<RoomId, serde_json::Value> = HashMap::new();
        for (room_id, events) in self.left_room_events.drain() {
            let room = serde_json::json!({
                "state": {
                    "events": [],
                },
                "timeline": {
                    "events": events,
                    "limited": false,
                    "prev_batch": prev_batch
                },
            });
            left_rooms.insert(room_id, room);
        }
        let mut invited_rooms: HashMap<RoomId, serde_json::Value> = HashMap::new();
        for (room_id, events) in self.invited_room_events.drain() {
            let room = serde_json::json!({
                "invite_state": {
                    "events": events,
                },
            });
            invited_rooms.insert(room_id, room);
        }
        let body = serde_json::json! {
            {
                "device_one_time_keys_count": {},
                "next_batch": next_batch,
                "device_lists": {
                    "changed": [],
                    "left": []
                },
                "rooms": {
                    "invite": invited_rooms,
                    "join": joined_rooms,
                    "leave": left_rooms,
                },
                "to_device": {
                    "events": []
                },
                "presence": {
                    "events": []
                }
            }
        };
        
        
        self.clear();
        body
    }
    
    
    
    
    
    
    
    
    
    pub fn build_sync_response(&mut self) -> SyncResponse {
        let body = self.build_json_sync_response();
        let response = Response::builder().body(serde_json::to_vec(&body).unwrap()).unwrap();
        SyncResponse::try_from_http_response(response).unwrap()
    }
    fn generate_sync_token(&self) -> String {
        format!("t392-516_47314_0_7_1_1_1_11444_{}", self.batch_counter)
    }
    pub fn clear(&mut self) {
        self.account_data.clear();
        self.ephemeral.clear();
        self.invited_room_events.clear();
        self.joined_room_events.clear();
        self.left_room_events.clear();
        self.presence_events.clear();
        self.state_events.clear();
    }
}
pub enum SyncResponseFile {
    All,
    Default,
    DefaultWithSummary,
    Invite,
    Leave,
    Voip,
}
pub fn sync_response(kind: SyncResponseFile) -> SyncResponse {
    let data: &JsonValue = match kind {
        SyncResponseFile::All => &test_json::MORE_SYNC,
        SyncResponseFile::Default => &test_json::SYNC,
        SyncResponseFile::DefaultWithSummary => &test_json::DEFAULT_SYNC_SUMMARY,
        SyncResponseFile::Invite => &test_json::INVITE_SYNC,
        SyncResponseFile::Leave => &test_json::LEAVE_SYNC,
        SyncResponseFile::Voip => &test_json::VOIP_SYNC,
    };
    let response = Response::builder().body(data.to_string().as_bytes().to_vec()).unwrap();
    SyncResponse::try_from_http_response(response).unwrap()
}
pub fn response_from_file(json: &serde_json::Value) -> Response<Vec<u8>> {
    Response::builder().status(200).body(json.to_string().as_bytes().to_vec()).unwrap()
}