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
//! The [`Bot`] struct and server setup.

use crate::{core::Core, request::CallbackAPIRequest};
use rocket::{
    config::{Config, Environment},
    http::Status,
    State,
};
use rocket_contrib::json::Json;
use rvk::APIClient;
use std::sync::{Arc, Mutex};

/// The string `ok` which needs to be sent in response to every Callback API
/// request.
const VK_OK: &'static str = "ok";

/// [`Bot`] represents a chat bot, and hands received requests to [`Core`].
#[derive(Debug, Clone)]
pub struct Bot {
    api: Arc<Mutex<APIClient>>,
    confirmation_token: String,
    group_id: i32,
    secret: String,
    port: u16,
    core: Core,
}

impl Bot {
    /// Creates a new [`Bot`].
    #[must_use = "the bot does nothing unless started via `.start()`"]
    pub fn new(
        vk_token: &str,
        confirmation_token: &str,
        group_id: i32,
        secret: &str,
        port: u16,
        core: Core,
    ) -> Self {
        Self {
            api: Arc::new(Mutex::new(APIClient::new(vk_token.into()))),
            confirmation_token: confirmation_token.into(),
            group_id,
            secret: secret.into(),
            port,
            core,
        }
    }

    /// Alias for `self.core.handle(req, self.api())`.
    pub fn handle(&self, req: &CallbackAPIRequest) {
        self.core.handle(req, self.api());
    }

    /// Starts this [`Bot`], consuming `self`.
    ///
    /// # Panics
    /// - if Rocket was not able to launch.
    pub fn start(self) -> ! {
        info!("starting bot...");

        let err = rocket::custom(
            Config::build(Environment::Production)
                .address("0.0.0.0")
                .port(self.port)
                .unwrap(),
        )
        .mount("/", routes![post, get])
        .manage(self)
        .launch();

        panic!("{}", err);
    }

    /// Returns the [`rvk::APIClient`] stored in this [`Bot`].
    pub fn api(&self) -> Arc<Mutex<APIClient>> {
        Arc::clone(&self.api)
    }

    /// Returns the confirmation token stored in this [`Bot`].
    pub fn confirmation_token(&self) -> &String {
        &self.confirmation_token
    }

    /// Returns the group ID stored in this [`Bot`].
    pub fn group_id(&self) -> i32 {
        self.group_id
    }

    /// Returns the secret stored in this [`Bot`].
    pub fn secret(&self) -> &String {
        &self.secret
    }
}

/// Handles `GET` requests by returning
/// [`rocket::http::Status::MethodNotAllowed`].
#[get("/")]
fn get() -> Status {
    debug!("received a GET request");
    Status::MethodNotAllowed
}

/// Handles `POST` requests by first checking that secret and group ID are
/// correct, and then responds with either confirmation token (if that is what
/// was requested) or [`VK_OK`] in the other case.
#[post("/", format = "json", data = "<data>")]
fn post(data: Json<CallbackAPIRequest>, state: State<Bot>) -> Result<String, Status> {
    let bot = &*state;

    match &data {
        x if x.secret() != bot.secret() => {
            debug!("received a POST request with invalid `secret`");
            Err(Status::Forbidden)
        }
        x if x.group_id() != bot.group_id() => {
            debug!("received a POST request with invalid `group_id`");
            Err(Status::Forbidden)
        }
        x if x.r#type() == "confirmation" => {
            debug!("responded with confirmation token");
            Ok(bot.confirmation_token().clone())
        }
        _ => {
            bot.handle(&data);
            Ok(VK_OK.into())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn get_returns_405() {
        assert_eq!(get(), Status::MethodNotAllowed);
    }

    fn post_test(secret: &str, group_id: i32, event: &str) -> Result<String, Status> {
        let rocket = rocket::ignite().manage(Bot::new(
            "vk_token",
            "confirmation_token",
            1,
            "secret",
            12345,
            Default::default(),
        ));

        post(
            Json(CallbackAPIRequest::new(
                secret,
                group_id,
                event,
                Default::default(),
            )),
            State::from(&rocket).unwrap(),
        )
    }

    #[test]
    fn post_invalid_secret_returns_403() {
        assert_eq!(post_test("wrong_secret", 1, ""), Err(Status::Forbidden));
    }

    #[test]
    fn post_invalid_group_id_returns_403() {
        assert_eq!(post_test("secret", 1337, ""), Err(Status::Forbidden));
    }

    #[test]
    fn post_confirmation_returns_confirmation_token() {
        assert_eq!(
            post_test("secret", 1, "confirmation"),
            Ok("confirmation_token".to_string())
        );
    }
}