summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: d8c51229c43d127eeb5f81c0afc53651ad7f696c (plain)
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
use std::{
    error::Error,
    net::SocketAddr,
    sync::Arc,
    collections::HashMap,
    num::NonZeroUsize,
};
use futures::stream::StreamExt;

mod types;
mod conn;
mod minesweeper;
use types::*;

use tokio::sync::RwLock;

const FONT_FILE: &[u8] = include_bytes!("../assets/VT323-Regular.ttf");
const CONF_FILE: &str = "./conf.json";

fn main() -> Result<(), Box<dyn Error>> {
    let conf = Config {
        cert: "./cert.pem".to_owned(),
        pkey: "./cert.rsa".to_owned(),
        index_pg: "./assets/index.html".to_owned(),
        room_pg: "./assets/room.html".to_owned(),
        client_code: "./assets/client.js".to_owned(),
        stylesheet: "./assets/style.css".to_owned(),
        socket_addr: ([0,0,0,0],31235).into(),
    };

    tokio_main(conf)
}

#[tokio::main]
async fn tokio_main(conf: Config) -> Result<(), Box<dyn Error>> {
    let conf_file: serde_json::Value = serde_json::from_str(&tokio::fs::read_to_string(CONF_FILE).await?)?;
    let area_limit: usize = conf_file.get("area_limit")
        .expect("no area_limit field in the conf.json file")
        .as_u64().expect("area_limit not a number") as usize;
    let room_limit: usize = conf_file.get("room_limit")
        .expect("no room_limit field in the conf.json file")
        .as_u64().expect("room_limit not a number") as usize;
    let rooms: RoomMap = Arc::new(RwLock::new(HashMap::new()));
    let public_rooms = Arc::new(RwLock::new(HashMap::new()));
    use warp::*;

    let index = path::end().and(fs::file(conf.index_pg.clone()));
    let style = path!("s.css").and(fs::file(conf.stylesheet.clone()));
    let code = path!("c.js").and(fs::file(conf.client_code.clone()));
    let font = path!("f.ttf").map(|| FONT_FILE);
    let listing = {
        let rooms = rooms.clone();
        let pubs = public_rooms.clone();
        path!("rlist").and_then(move || {
            let rooms = rooms.clone();
            let pubs = pubs.clone();
            async move {
                let roomsl = rooms.read().await;
                let pubsl = pubs.read().await;
                let rooms_pcount = futures::stream::iter(pubsl.iter())
                    .then(|(id, _):(&RoomId,_)| {
                        let roomsl = roomsl.clone();
                        async move {
                            let room = roomsl.get(id).unwrap().read().await;
                            let pcount = room.players.read().await.len();
                            (id.clone(), (pcount, room.conf.player_cap))
                        }
                    })
                    .collect::<HashMap<RoomId,_>>().await;
                let resp = (&*pubsl, rooms_pcount);
                Ok::<_,std::convert::Infallible>(
                    reply::json(&resp)
                )
            }
        })
    };
    let roomspace = {
        let rooms = rooms.clone();

        path!("rspace").and_then(move || {
            let r = rooms.clone();
            async move {
                let empty_len = empty_rooms(r.clone()).await.len();
                let space = room_limit - r.read().await.len() + empty_len;
                Ok::<_,std::convert::Infallible>(
                    hyper::Response::builder()
                        .status(hyper::StatusCode::OK)
                        .body(hyper::Body::from(space.to_string()))
                        .unwrap()
                )
            }
        })
    };
    let rform_recv = {
        let rooms = rooms.clone();
        let pubs = public_rooms.clone();
        post().and(path("r")).and(body::content_length_limit(4096)).and(body::form())
        .and_then(move |rinfo: HashMap<String, String>| {
            println!("{:?}", rinfo);
            let rooms = rooms.clone();
            let pubs = pubs.clone();
            async move {
                let slots_available = room_limit - rooms.read().await.len();
                let empty = empty_rooms(rooms.clone()).await;
                if slots_available < 1 {
                    if slots_available + empty.len() > 0 {
                        remove_room(rooms.clone(), pubs.clone(), empty[0].clone()).await;
                    } else {
                        return Err(reject::custom(NoRoomSlots));
                    }
                }

                if let (Some(w),Some(h),Some(num),Some(denom),access,asfm,limit) = (
                    rinfo.get("rwidth").and_then(|wt| wt.parse::<NonZeroUsize>().ok()),
                    rinfo.get("rheight").and_then(|ht| ht.parse::<NonZeroUsize>().ok()),
                    rinfo.get("rration").and_then(|nt| nt.parse::<usize>().ok()),
                    rinfo.get("rratiod").and_then(|dt| dt.parse::<NonZeroUsize>().ok()),
                    rinfo.get("raccess"),
                    rinfo.get("ralwayssafe1move"),
                    rinfo.get("rlimit").and_then(|l| l.parse::<usize>().ok()),
                    ) {
                    if w.get()*h.get() > area_limit {
                        return Err(reject::custom(BoardTooBig))
                    }
                    let board_conf = minesweeper::BoardConf { w, h, mine_ratio: (num,denom), always_safe_first_move: asfm.is_some() };
                    let mut rooms = rooms.write().await;
                    let uid = types::RoomId::new_in(&rooms);
                    let name = {
                        let n = rinfo.get("rname").unwrap().to_owned();
                        if n.is_empty() { uid.to_string() } else { n }
                    };
                    let players = PlayerMap::default();
                    let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
                    let handle = tokio::spawn(gameloop(cmd_rx, players.clone(), board_conf));
                    let room_conf = RoomConf {
                        name,
                        player_cap: match limit { Some(i) => i, None => usize::MAX },
                        public: access.is_some(),
                        board_conf,
                    };
                    let new_room = Room {
                        conf: room_conf,
                        players,
                        driver: handle,
                        cmd_stream: cmd_tx,
                    };
                    if access.is_some() {
                        pubs.write().await.insert(uid.clone(), serde_json::to_string(&new_room.conf).unwrap());
                    }
                    rooms.insert(uid.clone(), Arc::new(RwLock::new(new_room)));

                    Ok(
                    hyper::Response::builder()
                       .status(hyper::StatusCode::SEE_OTHER)
                       .header(hyper::header::LOCATION, format!("/room/{uid}"))
                       .body(hyper::Body::empty())
                       .unwrap()
                    )
                } else { Err(reject::custom(BadFormData)) }
            }
        })
    };
    let room = {
        let rooms_ws = rooms.clone();
        let rooms_lobby = rooms.clone();
        let prefix = get().and(path!("room" / String / ..));

        // Fixme: better errors
        prefix.and(path!("ws"))
            .and(ws())
            .and(addr::remote())
            .and_then(move |id: String, websocket: warp::ws::Ws, saddr: Option<SocketAddr>| {
                let rooms = rooms_ws.clone();
                async move {
                    let id = RoomId {0: id};
                    match rooms.read().await.get(&id).map(|x| x.clone()) {
                        Some(r) => {
                            println!("{id} I: conn from {saddr:?}");
                            Ok(websocket.on_upgrade(move |socket| {
                                conn::lobby(socket, saddr.expect("socket without address"), (id,r.clone()))
                            }))
                        },
                        None => {
                            println!("I: conn from {saddr:?} into inexistent room {id}");
                            Err(reject())
                        }
                    }
                }
            })
            .or(prefix.and(path::end())
                .and(fs::file(conf.room_pg.clone()))
                .then(move |id: String, f: fs::File| {
                    let rooms = rooms_lobby.clone();
                    async move {
                        if rooms.read().await.contains_key(&RoomId {0: id}) {
                            f.into_response()
                        } else {
                            reply::with_status("No such room", http::StatusCode::BAD_REQUEST).into_response()
                        }
                    }
                })
            )
    };


    let route = get()
        .and(index)
        .or(style)
        .or(code)
        .or(font)
        .or(listing)
        .or(roomspace)
        .or(rform_recv)
        .or(room)
        .recover(error_handler);

    let server = warp::serve(route)
        .tls()
        .cert_path(conf.cert)
        .key_path(conf.pkey)
        .run(conf.socket_addr);
    println!("Serving on {}", conf.socket_addr);
    server.await;
    Ok(())
}

// If a move is made, broadcast new board, else just send current board
async fn gameloop(mut move_rx: tokio::sync::mpsc::UnboundedReceiver<MetaMove>, players: PlayerMapData, bconf: minesweeper::BoardConf) {
    use minesweeper::*;
    use flate2::{ Compression, write::DeflateEncoder };
    use std::io::Write;
    let mut game = Game::new(bconf);
    let mut latest_player_name = None;
    while let Some(req) = move_rx.recv().await {
        let done = game.phase == Phase::Die || game.phase == Phase::Win;
        match req {
            MetaMove::Move(m, o) => if !done {
                game = game.act(m);
                if game.phase == Phase::Win || game.phase == Phase::Die {
                    game.board = game.board.grade();
                }
                latest_player_name = players.read().await.get(&o).map(|p| p.name.clone());
            },
            MetaMove::Dump => (),
            MetaMove::Reset => { game = Game::new(bconf); },
        }
        use warp::ws::Message;
        let mut board_encoder = DeflateEncoder::new(Vec::new(), Compression::default());
        board_encoder.write_all(&game.board.render()).unwrap();
        let compressed_board = board_encoder.finish().unwrap();
        let mut reply = vec![Message::binary(compressed_board)];
        let lpname = latest_player_name.as_ref().map(|s| s.as_str()).unwrap_or("unknown player");
        match game.phase {
            Phase::Win => { reply.push(Message::text(format!("win {lpname}"))); },
            Phase::Die => { reply.push(Message::text(format!("lose {lpname}"))); },
            _ => (),
        }
        {
            let peers = players.read().await;
            for (addr, p) in peers.iter() {
                for r in reply.iter() {
                    if let Err(e) = p.conn.tx.send(r.clone()) {
                        println!("couldn't send game update {r:?} to {addr}: {e}");
                    }
                }
            }
        }
    }
}

use warp::{ reject::{ Reject, Rejection }, reply::{ self, Reply }, http::StatusCode };
#[derive(Debug)]
struct BadFormData;
impl Reject for BadFormData {}

#[derive(Debug)]
struct BoardTooBig;
impl Reject for BoardTooBig {}

#[derive(Debug)]
struct NoRoomSlots;
impl Reject for NoRoomSlots {}

async fn error_handler(err: Rejection) -> Result<impl Reply, std::convert::Infallible> {
    if err.is_not_found() { Ok(reply::with_status("No such file", StatusCode::NOT_FOUND)) }
    else if let Some(_e) = err.find::<BadFormData>() {
        Ok(reply::with_status("Bad form data", StatusCode::BAD_REQUEST))
    } else if let Some(_e) = err.find::<BoardTooBig>() {
        Ok(reply::with_status("Board too big", StatusCode::BAD_REQUEST))
    } else if let Some(_e) = err.find::<NoRoomSlots>() {
        Ok(reply::with_status("No more rooms slots", StatusCode::BAD_REQUEST))
    } else {
        println!("unhandled rejection: {err:?}");
        Ok(reply::with_status("Server error", StatusCode::INTERNAL_SERVER_ERROR))
    }
}

async fn empty_rooms(rooms: RoomMap) -> Vec<RoomId> {
    let rl = rooms.read().await;
    futures::stream::iter(rl.iter())
        .filter_map(|(id,roomarc)| async move {
            let rrl = roomarc.read().await;
            let rrrl = rrl.players.read().await;
            if rrrl.len() == 0 { Some(id.clone()) } else { None }
        })
        .collect::<Vec<RoomId>>().await
}

async fn remove_room<T>(rooms: RoomMap, pubs: Arc<RwLock<HashMap<RoomId,T>>>, id: RoomId) {
    {
        let mut rwl = rooms.write().await;
        rwl.remove(&id);
    }
    {
        let mut pwl = pubs.write().await;
        pwl.remove(&id);
    }
}