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
use std::path::PathBuf;
use std::sync::mpsc;

use fehler::throws;
use gotham::handler::HandlerError;
use gotham::helpers::http::response::create_empty_response;
use gotham::hyper::{body, Body, Response, StatusCode};
use gotham::middleware::state::StateMiddleware;
use gotham::pipeline::single_pipeline;
use gotham::pipeline::single_middleware;
use gotham::router::builder::{DefineSingleRoute, build_router};
use gotham::router::builder::DrawRoutes;
use gotham::router::Router;
use gotham::state::{State, FromState};

use crate::{GSIConfig, Error, install_dir, update};

/// a server that listens for GSI updates
pub struct GSIServer {
    port: u16,
    config: GSIConfig,
    installed: bool,
    listeners: Vec<Box<dyn FnMut(&update::Update)>>,
}

impl GSIServer {
    /// create a new server with the given configuration and port
    pub fn new(config: GSIConfig, port: u16) -> Self {
        Self {
            port,
            config,
            installed: false,
            listeners: vec![],
        }
    }

    /// install this server's configuration into the given `/path/to/csgo/cfg/` folder
    #[throws]
    pub fn install_into<P: Into<PathBuf>>(&mut self, cfg_folder: P) {
        self.config.install_into(cfg_folder, self.port)?;
        self.installed = true;
    }

    /// install this server's configuration into the autodiscovered `/path/to/csgo/cfg/` folder, if it can be found
    #[throws]
    pub fn install(&mut self) {
        self.install_into(install_dir::discover_cfg_folder()?)?;
    }

    /// add an update listener
    pub fn add_listener<F: 'static + FnMut(&update::Update)>(&mut self, listener: F) {
        self.listeners.push(Box::new(listener));
    }

    /// run the server (will block indefinitely)
    #[throws]
    pub async fn run(mut self) {
        #[cfg(feature = "autoinstall")]
        if !self.installed {
            self.install()?;
        }

        let (tx, rx) = mpsc::sync_channel(128);

        let port = self.port;
        tokio::spawn(gotham::init_server(("127.0.0.1", port), router(tx)));

        for update in rx {
            for callback in &mut self.listeners {
                callback(&update)
            }
        }
    }
}

#[derive(Clone, StateData)]
struct UpdateHandler {
    inner: mpsc::SyncSender<update::Update>,
}

impl UpdateHandler {
    fn new(tx: &mpsc::SyncSender<update::Update>) -> Self {
        Self {
            inner: tx.clone()
        }
    }

    fn send(&self, update: update::Update) {
        self.inner.send(update).expect("failed to send update back to main thread");
    }
}

#[throws((State, HandlerError))]
pub async fn handle_update(mut state: State) -> (State, Response<Body>) {
    let body = state.try_take::<Body>();
    let body = match body {
        Some(body) => body,
        None => {
            let response = create_empty_response(&state, StatusCode::BAD_REQUEST);
            return (state, response);
        }
    };
    let body = body::to_bytes(body).await;
    let body = match body {
        Ok(body) => body,
        Err(err) => {
            eprintln!("{}", err);
            let response = create_empty_response(&state, StatusCode::INTERNAL_SERVER_ERROR);
            return (state, response);
        }
    };
    let json_value = serde_json::from_slice::<serde_json::Value>(body.as_ref());
    let json_value = match json_value {
        Ok(json_value) => json_value,
        Err(err) => {
            println!("JSON parsing error: {}", err);
            if let Ok(data) = ::std::str::from_utf8(body.as_ref()) {
                println!("{}\n", data);
            }
            let response = create_empty_response(&state, StatusCode::INTERNAL_SERVER_ERROR);
            return (state, response);
        }
    };
    let data = serde_json::from_value::<update::Update>(json_value);
    let data = match data {
        Ok(data) => data,
        Err(err) => {
            println!("Update parsing error: {}", err);
            if let Ok(data) = ::std::str::from_utf8(body.as_ref()) {
                println!("{}\n", data);
            }
            let response = create_empty_response(&state, StatusCode::INTERNAL_SERVER_ERROR);
            return (state, response);
        }
    };
    // TODO verify auth
    {
        let update_handler = UpdateHandler::borrow_from(&state);
        update_handler.send(data);
    }
    let response = create_empty_response(&state, StatusCode::OK);
    (state, response)
}

fn router(tx: mpsc::SyncSender<update::Update>) -> Router {
    let update_handler = UpdateHandler::new(&tx);

    let middleware = StateMiddleware::new(update_handler);
    let pipeline = single_middleware(middleware);
    let (chain, pipelines) = single_pipeline(pipeline);

    build_router(chain, pipelines, |route| {
        route
            .post("/")
            .to_async(handle_update);
    })
}