Skip to main content

manabrew_relay_protocol/
directory.rs

1//! The room directory: the relay's HTTP listing contract at [`ROOMS_PATH`].
2//! Field names are camelCase, unlike the WebSocket messages, because the
3//! publish calls follow Forge's room directory (Card-Forge/forge#13115).
4use serde::{Deserialize, Serialize};
5use ts_rs::TS;
6
7use crate::{RoomInfo, RoomStatus};
8
9pub const ROOMS_PATH: &str = "/api/v1/rooms";
10
11pub const MAX_NAME_CHARS: usize = 120;
12pub const MAX_FORMAT_CHARS: usize = 240;
13pub const MAX_LANGUAGE_CHARS: usize = 32;
14pub const MAX_VERSION_CHARS: usize = 80;
15pub const MAX_DESCRIPTION_CHARS: usize = 240;
16pub const MAX_ADDRESS_CHARS: usize = 253;
17pub const ADDRESS_FORBIDDEN_CHARS: &str = "[]/?#@\\";
18pub const MIN_CAPACITY: u8 = 2;
19pub const MAX_CAPACITY: u8 = 16;
20
21/// The app that can join a listing.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
23#[ts(export, export_to = "directory/index.ts")]
24#[serde(rename_all = "lowercase")]
25pub enum DirectoryClient {
26    Forge,
27    Manabrew,
28}
29
30/// How a joiner reaches the game.
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
32#[ts(export, export_to = "directory/index.ts")]
33#[serde(tag = "connection", rename_all = "lowercase")]
34pub enum ListingConnection {
35    /// The host listens here and the joiner connects to it.
36    Direct { address: String, port: u16 },
37    /// A room on this relay: `ClientMessage::JoinRoom` with the listing `id`,
38    /// then `ServerMessage::RoomTransport` hands members their endpoints.
39    Relay,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
43#[ts(export, export_to = "directory/index.ts")]
44#[serde(rename_all = "lowercase")]
45pub enum ListingStatus {
46    Open,
47    Full,
48    Started,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
52#[ts(export, export_to = "directory/index.ts")]
53#[serde(rename_all = "camelCase")]
54pub struct Listing {
55    pub id: String,
56    pub client: DirectoryClient,
57    pub name: String,
58    pub format: String,
59    pub language: String,
60    pub capacity: u8,
61    pub players: u8,
62    pub available_slots: u8,
63    #[serde(flatten)]
64    #[ts(flatten)]
65    pub connection: ListingConnection,
66    pub version: String,
67    pub description: String,
68    pub status: ListingStatus,
69    pub updated_at: String,
70}
71
72impl Listing {
73    /// A relay room as the directory shows it. `None` when a stranger cannot
74    /// join it from a listing: nobody is seated, or it needs a password.
75    pub fn from_room(room: &RoomInfo, updated_at: String) -> Option<Listing> {
76        let players = room.players.len() as u8;
77        if players == 0 || room.password_protected {
78            return None;
79        }
80        let status = match room.status {
81            RoomStatus::Lobby if players < room.max_players => ListingStatus::Open,
82            RoomStatus::Lobby => ListingStatus::Full,
83            RoomStatus::InGame | RoomStatus::Finished => ListingStatus::Started,
84        };
85        Some(Listing {
86            id: room.room_id.clone(),
87            client: DirectoryClient::Manabrew,
88            name: room.room_name.clone(),
89            format: format!("{:?}", room.format),
90            language: String::new(),
91            capacity: room.max_players,
92            players,
93            available_slots: room.max_players.saturating_sub(players),
94            connection: ListingConnection::Relay,
95            version: room.protocol_version.to_string(),
96            description: String::new(),
97            status,
98            updated_at,
99        })
100    }
101}
102
103/// Body of `POST` (publish) and of `PUT` or `PATCH` (update). A published
104/// listing is always [`ListingConnection::Direct`].
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106#[serde(rename_all = "camelCase")]
107pub struct ListingAnnouncement {
108    pub client: DirectoryClient,
109    pub name: String,
110    pub format: String,
111    pub language: String,
112    pub capacity: u8,
113    pub players: u8,
114    pub address: String,
115    pub port: u16,
116    pub version: String,
117    pub description: String,
118    /// Required `true` on publish: the host agreed to show the address.
119    #[serde(default)]
120    pub public_address_accepted: bool,
121    /// Required on update; publish always opens the listing.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub status: Option<ListingStatus>,
124}
125
126impl ListingAnnouncement {
127    pub fn is_valid(&self) -> bool {
128        self.client != DirectoryClient::Manabrew
129            && text_fits(&self.name, MAX_NAME_CHARS)
130            && text_fits(&self.format, MAX_FORMAT_CHARS)
131            && !self.format.trim().is_empty()
132            && text_fits(&self.language, MAX_LANGUAGE_CHARS)
133            && text_fits(&self.version, MAX_VERSION_CHARS)
134            && text_fits(&self.description, MAX_DESCRIPTION_CHARS)
135            && text_fits(&self.address, MAX_ADDRESS_CHARS)
136            && !self.address.is_empty()
137            && !self
138                .address
139                .contains(|c: char| c.is_whitespace() || ADDRESS_FORBIDDEN_CHARS.contains(c))
140            && (MIN_CAPACITY..=MAX_CAPACITY).contains(&self.capacity)
141            && (1..=self.capacity).contains(&self.players)
142            && self.port != 0
143    }
144
145    pub fn into_listing(self, id: String, status: ListingStatus, updated_at: String) -> Listing {
146        Listing {
147            id,
148            client: self.client,
149            name: self.name,
150            format: self.format,
151            language: self.language,
152            capacity: self.capacity,
153            players: self.players,
154            available_slots: self.capacity - self.players,
155            connection: ListingConnection::Direct {
156                address: self.address,
157                port: self.port,
158            },
159            version: self.version,
160            description: self.description,
161            status,
162            updated_at,
163        }
164    }
165}
166
167fn text_fits(value: &str, max_chars: usize) -> bool {
168    value.chars().count() <= max_chars && !value.chars().any(char::is_control)
169}
170
171/// Query of `GET`: whose listings to return.
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub struct ListingsQuery {
174    pub client: DirectoryClient,
175}
176
177/// Response of `GET`.
178#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
179#[ts(export, export_to = "directory/index.ts")]
180pub struct Listings {
181    pub rooms: Vec<Listing>,
182}
183
184/// Query of update and close: the published listing they act on.
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186pub struct PublishedListingQuery {
187    pub id: String,
188}
189
190/// Response of `POST`. `token` is the listing token: the publisher sends it
191/// as `Authorization: Bearer` to update or close this listing.
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193pub struct PublishedListing {
194    pub id: String,
195    pub token: String,
196}
197
198/// Response of `PUT` and `PATCH`.
199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200pub struct ListingSaved {
201    pub saved: bool,
202}
203
204/// Response of `DELETE`.
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
206pub struct ListingClosed {
207    pub closed: bool,
208}