1use std::collections::HashMap;
2use std::time::Instant;
3
4use crate::chat::ChatHistory;
5use crate::protocol::{
6 DraftConfig, EngineKind, GameFormat, PlayerDeckInfo, RoomInfo, RoomPlayerInfo, RoomStatus,
7 SealedConfig, TransportEndpoint, TransportMember,
8};
9use crate::replay::GameReplayCache;
10use manabrew_protocol::deck_dto::Deck;
11
12#[derive(Debug, Clone)]
13pub struct RoomSlot {
14 pub player_id: String,
15 pub username: String,
16 pub ready: bool,
17 pub connected: bool,
18 pub is_bot: bool,
19 pub selected_deck_name: Option<String>,
20 pub selected_deck: Option<Deck>,
21 pub published_deck_id: Option<String>,
22 pub selected_commander_name: Option<String>,
23 pub avatar_url: Option<String>,
24}
25
26#[derive(Debug, Clone)]
27pub struct RoomObserver {
28 pub player_id: String,
29 pub connected: bool,
30}
31
32#[derive(Debug)]
33pub struct Room {
34 pub room_id: String,
35 pub room_name: String,
36 pub protocol_version: u32,
37 pub host_player_id: String,
38 pub host_username: String,
39 pub hosted: bool,
40 pub official: bool,
41 pub password: Option<String>,
42 pub max_players: u8,
43 pub format: GameFormat,
44 pub engine: EngineKind,
45 pub status: RoomStatus,
46 pub players: Vec<RoomSlot>,
47 pub observers: Vec<RoomObserver>,
48 pub draft_config: Option<DraftConfig>,
49 pub sealed_config: Option<SealedConfig>,
50 pub reconnect_timeout_s: u32,
51 pub table_style: Option<String>,
52 pub replay: Option<GameReplayCache>,
53 pub resume_token: String,
54 pub humanless_since: Option<Instant>,
55 pub limited_session_id: Option<String>,
56 pub draft_clock: Option<crate::draft_clock::DraftClock>,
57 pub parent_limited_room: Option<String>,
58 pub limited_matches: Vec<String>,
59 pub transports: HashMap<String, TransportEndpoint>,
61 pub chat: ChatHistory,
62}
63
64impl Room {
65 #[allow(clippy::too_many_arguments)]
66 pub fn new(
67 room_id: String,
68 room_name: String,
69 protocol_version: u32,
70 host_player_id: String,
71 host_username: String,
72 max_players: u8,
73 format: GameFormat,
74 engine: EngineKind,
75 host_plays: bool,
76 draft_config: Option<DraftConfig>,
77 sealed_config: Option<SealedConfig>,
78 official: bool,
79 password: Option<String>,
80 reconnect_timeout_s: u32,
81 table_style: Option<String>,
82 ) -> Self {
83 let max_players = max_players.clamp(2, 8);
84 let (players, observers) = if host_plays {
85 (
86 vec![RoomSlot {
87 player_id: host_player_id.clone(),
88 username: host_username.clone(),
89 ready: false,
90 connected: true,
91 is_bot: false,
92 selected_deck_name: None,
93 selected_deck: None,
94 published_deck_id: None,
95 selected_commander_name: None,
96 avatar_url: None,
97 }],
98 vec![],
99 )
100 } else {
101 (
102 vec![],
103 vec![RoomObserver {
104 player_id: host_player_id.clone(),
105 connected: true,
106 }],
107 )
108 };
109 Room {
110 room_id,
111 room_name,
112 protocol_version,
113 host_player_id: host_player_id.clone(),
114 host_username,
115 hosted: !host_plays,
116 official,
117 password,
118 max_players,
119 format,
120 engine,
121 status: RoomStatus::Lobby,
122 players,
123 observers,
124 draft_config,
125 sealed_config,
126 reconnect_timeout_s,
127 table_style,
128 replay: None,
129 resume_token: uuid::Uuid::new_v4().to_string(),
130 humanless_since: None,
131 limited_session_id: None,
132 draft_clock: None,
133 parent_limited_room: None,
134 limited_matches: Vec::new(),
135 transports: HashMap::new(),
136 chat: ChatHistory::default(),
137 }
138 }
139
140 pub fn is_full(&self) -> bool {
141 self.players.len() >= self.max_players as usize
142 }
143
144 pub fn is_empty(&self) -> bool {
145 self.players.is_empty() && self.observers.is_empty()
146 }
147
148 pub fn is_limited_session(&self) -> bool {
149 matches!(
150 self.format,
151 GameFormat::Any | GameFormat::Draft | GameFormat::Sealed
152 ) && (self.draft_config.is_some() || self.sealed_config.is_some())
153 }
154
155 pub fn reset_lobby_settings(&mut self) {
156 if self.draft_config.is_none() && self.sealed_config.is_none() {
157 self.format = GameFormat::Any;
158 self.max_players = 4;
159 }
160 }
161
162 pub fn all_ready(&self) -> bool {
163 let min_players = if self.is_limited_session() { 1 } else { 2 };
164 let controller_id = self.controller_id();
165 self.players.len() >= min_players
166 && self
167 .players
168 .iter()
169 .filter(|p| Some(p.player_id.as_str()) != controller_id)
170 .all(|p| p.ready)
171 }
172
173 pub fn add_player(
174 &mut self,
175 player_id: String,
176 username: String,
177 is_bot: bool,
178 ) -> Result<(), String> {
179 if self.is_full() {
180 return Err("Room is full".into());
181 }
182 if self.status != RoomStatus::Lobby {
183 return Err("Game already started".into());
184 }
185 if self.players.iter().any(|p| p.player_id == player_id) {
186 return Err("Already in this room".into());
187 }
188 self.players.push(RoomSlot {
189 player_id,
190 username,
191 ready: false,
192 connected: true,
193 is_bot,
194 selected_deck_name: None,
195 selected_deck: None,
196 published_deck_id: None,
197 selected_commander_name: None,
198 avatar_url: None,
199 });
200 Ok(())
201 }
202
203 pub fn add_observer(&mut self, player_id: String, _username: String) -> Result<(), String> {
204 if self.players.iter().any(|p| p.player_id == player_id)
205 || self.observers.iter().any(|p| p.player_id == player_id)
206 {
207 return Err("Already in this room".into());
208 }
209 self.observers.push(RoomObserver {
210 player_id,
211 connected: true,
212 });
213 Ok(())
214 }
215
216 pub fn remove_player(&mut self, player_id: &str) -> Option<RoomSlot> {
217 if let Some(idx) = self.players.iter().position(|p| p.player_id == player_id) {
218 let slot = self.players.remove(idx);
219 if self.host_player_id == player_id && self.limited_session_id.is_none() {
220 let new_host = self
221 .players
222 .iter()
223 .find(|p| p.connected && !p.is_bot)
224 .or_else(|| self.players.iter().find(|p| !p.is_bot));
225 if let Some(new_host) = new_host {
226 self.host_player_id = new_host.player_id.clone();
227 self.host_username = new_host.username.clone();
228 }
229 }
230 Some(slot)
231 } else {
232 None
233 }
234 }
235
236 pub fn remove_observer(&mut self, player_id: &str) -> Option<RoomObserver> {
237 self.observers
238 .iter()
239 .position(|p| p.player_id == player_id)
240 .map(|idx| self.observers.remove(idx))
241 }
242
243 pub fn remove_participant(&mut self, player_id: &str) -> bool {
244 self.transports.remove(player_id);
245 self.remove_player(player_id).is_some() || self.remove_observer(player_id).is_some()
246 }
247
248 pub fn set_connected(&mut self, player_id: &str, connected: bool) {
249 if let Some(slot) = self.players.iter_mut().find(|p| p.player_id == player_id) {
250 slot.connected = connected;
251 return;
252 }
253 if let Some(observer) = self.observers.iter_mut().find(|p| p.player_id == player_id) {
254 observer.connected = connected;
255 }
256 }
257
258 #[allow(dead_code)]
260 pub fn all_disconnected(&self) -> bool {
261 self.players.iter().all(|p| !p.connected) && self.observers.iter().all(|p| !p.connected)
262 }
263
264 pub fn has_connected_human(&self) -> bool {
265 self.players.iter().any(|p| p.connected && !p.is_bot)
266 || self
267 .observers
268 .iter()
269 .any(|o| o.connected && !(self.hosted && o.player_id == self.host_player_id))
270 }
271
272 pub fn set_ready(&mut self, player_id: &str, ready: bool) -> Result<(), String> {
273 if let Some(slot) = self.players.iter_mut().find(|p| p.player_id == player_id) {
274 slot.ready = ready;
275 Ok(())
276 } else {
277 Err("Player not in room".into())
278 }
279 }
280
281 pub fn set_deck_selection(
282 &mut self,
283 player_id: &str,
284 deck_name: String,
285 deck: Deck,
286 published_deck_id: Option<String>,
287 commander_name: Option<String>,
288 avatar_url: Option<String>,
289 ) -> Result<(), String> {
290 if let Some(slot) = self.players.iter_mut().find(|p| p.player_id == player_id) {
291 slot.selected_deck_name = Some(deck_name);
292 slot.selected_deck = Some(deck);
293 slot.published_deck_id = published_deck_id;
294 slot.selected_commander_name = commander_name;
295 slot.avatar_url = avatar_url;
296 slot.ready = false;
297 Ok(())
298 } else {
299 Err("Player not in room".into())
300 }
301 }
302
303 pub fn has_selected_deck(&self, player_id: &str) -> bool {
304 self.players
305 .iter()
306 .find(|p| p.player_id == player_id)
307 .map(|p| p.selected_deck.is_some() && p.selected_deck_name.is_some())
308 .unwrap_or(false)
309 }
310
311 pub fn player_decks(&self) -> Vec<PlayerDeckInfo> {
312 self.players
313 .iter()
314 .filter_map(|p| {
315 p.selected_deck.clone().map(|deck| PlayerDeckInfo {
316 username: p.username.clone(),
317 deck_name: p
318 .selected_deck_name
319 .clone()
320 .unwrap_or_else(|| "Unknown Deck".to_string()),
321 deck,
322 published_deck_id: p.published_deck_id.clone(),
323 commander_name: p.selected_commander_name.clone(),
324 avatar_url: p.avatar_url.clone(),
325 })
326 })
327 .collect()
328 }
329
330 pub fn engine_survives_host_loss(&self) -> bool {
334 self.engine == EngineKind::Ironsmith && !self.hosted && self.limited_session_id.is_none()
335 }
336
337 pub fn migrate_host(&mut self) -> bool {
340 let Some(new_host) = self
341 .players
342 .iter()
343 .find(|p| p.connected && !p.is_bot && p.player_id != self.host_player_id)
344 else {
345 return false;
346 };
347 self.host_player_id = new_host.player_id.clone();
348 self.host_username = new_host.username.clone();
349 true
350 }
351
352 pub fn is_host(&self, player_id: &str) -> bool {
353 self.host_player_id == player_id
354 }
355
356 pub fn controller_id(&self) -> Option<&str> {
362 self.players
363 .iter()
364 .find(|p| !p.is_bot)
365 .or_else(|| self.players.first())
366 .map(|p| p.player_id.as_str())
367 }
368
369 pub fn is_controller(&self, player_id: &str) -> bool {
370 self.controller_id() == Some(player_id)
371 }
372
373 pub fn host_username(&self) -> String {
374 self.host_username.clone()
375 }
376
377 pub fn host_is_player(&self) -> bool {
378 self.players
379 .iter()
380 .any(|p| p.player_id == self.host_player_id)
381 }
382
383 pub fn host_connected(&self) -> bool {
384 self.players
385 .iter()
386 .any(|p| p.player_id == self.host_player_id && p.connected)
387 || self
388 .observers
389 .iter()
390 .any(|p| p.player_id == self.host_player_id && p.connected)
391 }
392
393 pub fn player_usernames(&self) -> Vec<String> {
394 self.players.iter().map(|p| p.username.clone()).collect()
395 }
396
397 #[allow(dead_code)]
399 pub fn player_ids(&self) -> Vec<String> {
400 self.players.iter().map(|p| p.player_id.clone()).collect()
401 }
402
403 pub fn connected_player_ids(&self) -> Vec<String> {
404 self.players
405 .iter()
406 .filter(|p| p.connected)
407 .map(|p| p.player_id.clone())
408 .chain(
409 self.observers
410 .iter()
411 .filter(|p| p.connected)
412 .map(|p| p.player_id.clone()),
413 )
414 .collect()
415 }
416
417 pub fn to_room_info(&self) -> RoomInfo {
418 RoomInfo {
419 room_id: self.room_id.clone(),
420 room_name: self.room_name.clone(),
421 protocol_version: self.protocol_version,
422 host: self.host_username(),
423 hosted: self.hosted,
424 official: self.official,
425 password_protected: self.password.is_some(),
426 players: self
427 .players
428 .iter()
429 .map(|p| RoomPlayerInfo {
430 username: p.username.clone(),
431 ready: p.ready,
432 connected: p.connected,
433 is_bot: p.is_bot,
434 selected_deck_name: p.selected_deck_name.clone(),
435 })
436 .collect(),
437 max_players: self.max_players,
438 format: self.format.clone(),
439 engine: self.engine,
440 reconnect_timeout_s: self.reconnect_timeout_s,
441 table_style: self.table_style.clone(),
442 status: self.status.clone(),
443 draft_config: self.draft_config.clone(),
444 sealed_config: self.sealed_config.clone(),
445 }
446 }
447}
448
449const MAX_DIRECT_ADDRS: usize = 16;
450const MAX_ADDR_LEN: usize = 64;
451
452impl Room {
453 pub fn participant_id_by_username(&self, username: &str) -> Option<String> {
455 if let Some(slot) = self.players.iter().find(|p| p.username == username) {
456 return Some(slot.player_id.clone());
457 }
458 (self.host_username == username).then(|| self.host_player_id.clone())
459 }
460
461 fn participant_username(&self, player_id: &str) -> Option<String> {
462 if let Some(slot) = self.players.iter().find(|p| p.player_id == player_id) {
463 return Some(slot.username.clone());
464 }
465 (self.host_player_id == player_id).then(|| self.host_username.clone())
466 }
467
468 pub fn set_transport(&mut self, player_id: &str, endpoint: Option<TransportEndpoint>) -> bool {
470 let participant = self.players.iter().any(|p| p.player_id == player_id)
471 || self.observers.iter().any(|p| p.player_id == player_id);
472 if !participant {
473 return false;
474 }
475 let Some(mut endpoint) = endpoint else {
476 self.transports.remove(player_id);
477 return true;
478 };
479 let taken = self.transports.iter().any(|(other, existing)| {
481 other != player_id && existing.endpoint_id == endpoint.endpoint_id
482 });
483 if taken {
484 return false;
485 }
486 endpoint
487 .direct_addrs
488 .retain(|addr| addr.len() <= MAX_ADDR_LEN);
489 endpoint.direct_addrs.truncate(MAX_DIRECT_ADDRS);
490 self.transports.insert(player_id.to_string(), endpoint);
491 true
492 }
493
494 pub fn transport_members(&self) -> Vec<TransportMember> {
496 let mut members: Vec<TransportMember> = self
497 .transports
498 .iter()
499 .filter_map(|(player_id, endpoint)| {
500 self.participant_username(player_id)
501 .map(|username| TransportMember {
502 username,
503 endpoint: endpoint.clone(),
504 host: player_id == &self.host_player_id,
505 })
506 })
507 .collect();
508 members.sort_by(|a, b| a.username.cmp(&b.username));
509 members
510 }
511
512 pub fn transport_host(&self) -> Option<TransportMember> {
513 self.transport_members().into_iter().find(|m| m.host)
514 }
515
516 pub fn transport_consented(&self) -> bool {
518 self.players
519 .iter()
520 .filter(|p| !p.is_bot)
521 .all(|p| self.transports.contains_key(&p.player_id))
522 }
523}
524
525#[cfg(test)]
526mod tests {
527 use super::*;
528
529 fn room(host_plays: bool) -> Room {
530 Room::new(
531 "r".into(),
532 "room".into(),
533 manabrew_relay_protocol::PROTOCOL_VERSION,
534 "host".into(),
535 "host".into(),
536 4,
537 GameFormat::Commander,
538 EngineKind::Forge,
539 host_plays,
540 None,
541 None,
542 false,
543 None,
544 60,
545 None,
546 )
547 }
548
549 #[test]
550 fn first_user_is_controller_in_hosted_room() {
551 let mut r = room(false);
552 assert!(r.is_host("host"));
553 assert!(!r.is_controller("host"));
554 r.add_player("human".into(), "human".into(), false).unwrap();
555 assert!(r.is_controller("human"));
556 r.add_player("bot".into(), "bot".into(), true).unwrap();
557 assert!(!r.is_controller("bot"));
558 }
559
560 #[test]
561 fn a_lost_host_hands_a_replicated_game_to_the_next_connected_human() {
562 let mut r = room(true);
563 r.engine = EngineKind::Ironsmith;
564 r.add_player("bot".into(), "bot".into(), true).unwrap();
565 r.add_player("away".into(), "away".into(), false).unwrap();
566 r.add_player("guest".into(), "guest".into(), false).unwrap();
567 assert!(r.engine_survives_host_loss());
568
569 r.set_connected("host", false);
570 r.set_connected("away", false);
571 assert!(r.migrate_host());
572 assert!(r.is_host("guest"));
573 assert_eq!(r.host_username(), "guest");
574
575 r.set_connected("guest", false);
577 assert!(!r.migrate_host());
578 assert!(r.is_host("guest"));
579 }
580
581 #[test]
582 fn engines_that_live_on_the_host_do_not_survive_losing_it() {
583 assert!(!room(true).engine_survives_host_loss());
584 }
585
586 #[test]
587 fn a_leaving_host_passes_the_room_to_a_connected_human_before_a_bot() {
588 let mut r = room(true);
589 r.add_player("bot".into(), "bot".into(), true).unwrap();
590 r.add_player("guest".into(), "guest".into(), false).unwrap();
591 r.remove_player("host");
592 assert!(r.is_host("guest"));
593 }
594
595 #[test]
596 fn only_room_members_are_addressable_by_name() {
597 let mut r = room(false);
598 r.add_player("p-human".into(), "human".into(), false)
599 .unwrap();
600 r.add_observer("p-watcher".into(), "watcher".into())
601 .unwrap();
602
603 assert_eq!(
604 r.participant_id_by_username("human"),
605 Some("p-human".into())
606 );
607 assert_eq!(r.participant_id_by_username("host"), Some("host".into()));
608 assert_eq!(r.participant_id_by_username("stranger"), None);
609 assert_eq!(r.participant_id_by_username("watcher"), None);
610 }
611
612 #[test]
613 fn an_endpoint_without_kinds_speaks_nothing() {
614 assert!(!endpoint("a").speaks(manabrew_relay_protocol::TRANSPORT_KIND_WEBRTC));
615
616 let browser = TransportEndpoint {
617 kinds: vec![manabrew_relay_protocol::TRANSPORT_KIND_WEBRTC.into()],
618 ..endpoint("b")
619 };
620 assert!(browser.speaks(manabrew_relay_protocol::TRANSPORT_KIND_WEBRTC));
621 assert!(!browser.speaks("other"));
622 }
623
624 fn endpoint(id: &str) -> TransportEndpoint {
625 TransportEndpoint {
626 endpoint_id: id.into(),
627 relay_url: None,
628 direct_addrs: vec![],
629 kinds: vec![],
630 }
631 }
632
633 #[test]
634 fn only_members_announce_and_nobody_takes_another_endpoint() {
635 let mut r = room(false);
636 r.add_player("human".into(), "human".into(), false).unwrap();
637 r.add_player("squatter".into(), "squatter".into(), false)
638 .unwrap();
639
640 assert!(r.set_transport("human", Some(endpoint("ep-human"))));
641 assert!(!r.set_transport("stranger", Some(endpoint("ep-stranger"))));
642 assert!(!r.set_transport("squatter", Some(endpoint("ep-human"))));
643 assert_eq!(r.transports["human"].endpoint_id, "ep-human");
644
645 r.set_transport("host", Some(endpoint("ep-host")));
646 assert_eq!(r.transport_host().unwrap().username, "host");
647 assert_eq!(r.transport_members().len(), 2);
648
649 r.remove_participant("human");
650 assert!(!r.transports.contains_key("human"));
651 }
652
653 #[test]
654 fn every_human_seat_has_to_announce_before_the_room_leaves_the_relay() {
655 let mut r = room(false);
656 r.add_player("alice".into(), "alice".into(), false).unwrap();
657 r.add_player("bob".into(), "bob".into(), false).unwrap();
658 r.add_player("bot".into(), "bot".into(), true).unwrap();
659 r.set_transport("host", Some(endpoint("ep-host")));
660
661 assert!(r.set_transport("alice", Some(endpoint("ep-alice"))));
662 assert!(!r.transport_consented(), "bob has not opted in");
663
664 assert!(r.set_transport("bob", Some(endpoint("ep-bob"))));
665 assert!(r.transport_consented(), "bots do not have to announce");
666
667 assert!(r.set_transport("bob", None));
668 assert!(!r.transport_consented());
669
670 r.remove_participant("bob");
671 assert!(r.transport_consented());
672 }
673
674 #[test]
675 fn an_announcement_cannot_flood_the_address_book() {
676 let mut r = room(false);
677 r.add_player("human".into(), "human".into(), false).unwrap();
678 let mut flood = endpoint("ep-human");
679 flood.direct_addrs = (0..64).map(|i| format!("10.0.0.{i}:1234")).collect();
680 flood.direct_addrs.push("x".repeat(MAX_ADDR_LEN + 1));
681
682 assert!(r.set_transport("human", Some(flood)));
683 let stored = &r.transports["human"].direct_addrs;
684 assert_eq!(stored.len(), MAX_DIRECT_ADDRS);
685 assert!(stored.iter().all(|addr| addr.len() <= MAX_ADDR_LEN));
686 }
687}