aboutsummaryrefslogtreecommitdiff
path: root/server/discover/src/main.rs
blob: f546cd6c0ffddeea9d117c02304e61e2ebe9cbc5 (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
/*
    Hurry Curry! - a game about cooking
    Copyright 2024 metamuffin

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/
#![feature(never_type)]
use anyhow::Result;
use http_body_util::Full;
use hurrycurry_protocol::registry::Entry;
use hyper::{
    body::Bytes, header::HeaderValue, server::conn::http1, service::service_fn, Response,
    StatusCode,
};
use hyper_util::rt::TokioIo;
use log::warn;
use mdns_sd::{ServiceDaemon, ServiceEvent};
use std::{cmp::Reverse, collections::HashMap, net::SocketAddr, sync::Arc};
use tokio::{net::TcpListener, spawn, sync::RwLock};

fn main() -> Result<()> {
    env_logger::init_from_env("LOG");
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(async_main())?;
}
async fn async_main() -> Result<!> {
    let mdns = ServiceDaemon::new()?;
    let mdns_events = mdns.browse("_hurrycurry._tcp.local.")?;

    let entries = Arc::new(RwLock::new(HashMap::<String, Entry>::new()));
    let entries2 = entries.clone();

    spawn(async move {
        while let Ok(event) = mdns_events.recv_async().await {
            match event {
                ServiceEvent::ServiceResolved(service_info) => {
                    entries2.write().await.insert(
                        service_info.get_fullname().to_owned(),
                        Entry {
                            name: service_info
                                .get_fullname()
                                .strip_suffix("._hurrycurry._tcp.local.")
                                .unwrap_or(service_info.get_fullname())
                                .to_owned(),
                            address: service_info
                                .get_addresses()
                                .iter()
                                .map(|a| {
                                    format!("ws://{}", SocketAddr::new(*a, service_info.get_port()))
                                })
                                .collect(),
                            players_online: service_info
                                .get_property_val_str("players")
                                .and_then(|p| p.parse().ok())
                                .unwrap_or(0),
                            last_game: 0,
                            version: service_info
                                .get_property_val_str("protocol")
                                .and_then(|v| {
                                    let (maj, min) = v.split_once(".")?;
                                    Some((maj.parse().ok()?, min.parse().ok()?))
                                })
                                .unwrap_or((0, 0)),
                        },
                    );
                }
                ServiceEvent::ServiceRemoved(_, fullname) => {
                    entries2.write().await.remove(&fullname);
                }
                _ => (),
            }
        }
    });

    let listener = TcpListener::bind("127.0.0.1:27033").await?;
    loop {
        let (stream, _) = listener.accept().await?;
        let entries = entries.clone();
        spawn(async move {
            if let Err(e) = http1::Builder::new()
                .serve_connection(
                    TokioIo::new(stream),
                    service_fn(move |_req| {
                        let entries = entries.clone();
                        async move {
                            Ok::<_, !>(match _req.uri().path() {
                                "/" => Response::new(Full::new(Bytes::from(
                                    "Hurry Curry! local discovery service",
                                ))),
                                "/v1/list" => {
                                    let mut ents = entries
                                        .read()
                                        .await
                                        .clone()
                                        .into_values()
                                        .collect::<Vec<_>>();
                                    ents.sort_by_key(|e| Reverse(e.players_online));

                                    let mut res = Response::new(Full::new(Bytes::from(
                                        serde_json::to_string(&ents).unwrap(),
                                    )));
                                    *res.status_mut() = StatusCode::OK;
                                    res.headers_mut().insert(
                                        "content-type",
                                        HeaderValue::from_static("application/json"),
                                    );
                                    res
                                }
                                _ => {
                                    let mut res =
                                        Response::new(Full::new(Bytes::from("not found")));
                                    *res.status_mut() = StatusCode::NOT_FOUND;
                                    res
                                }
                            })
                        }
                    }),
                )
                .await
            {
                warn!("conn failed: {e}");
            }
        });
    }
}