aboutsummaryrefslogtreecommitdiff
path: root/planetwars-server/src/routes/bots.rs
blob: 6d5d7df4eac8bf684599f7b8e5581ed2eba2f19a (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
use axum::extract::{Multipart, Path};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{body, Json};
use diesel::OptionalExtension;
use rand::distributions::Alphanumeric;
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::{self, json, value::Value as JsonValue};
use std::io::Cursor;
use std::path::PathBuf;
use thiserror;

use crate::db::bots::{self, CodeBundle};
use crate::db::ratings::{self, RankedBot};
use crate::db::users::User;
use crate::modules::bots::save_code_bundle;
use crate::{DatabaseConnection, BOTS_DIR};
use bots::Bot;

#[derive(Serialize, Deserialize, Debug)]
pub struct SaveBotParams {
    pub bot_name: String,
    pub code: String,
}

#[derive(Debug, thiserror::Error)]
pub enum SaveBotError {
    #[error("database error")]
    DatabaseError(#[from] diesel::result::Error),
    #[error("validation failed")]
    ValidationFailed(Vec<&'static str>),
    #[error("bot name already exists")]
    BotNameTaken,
}

impl IntoResponse for SaveBotError {
    fn into_response(self) -> Response {
        let (status, value) = match self {
            SaveBotError::BotNameTaken => (
                StatusCode::FORBIDDEN,
                json!({ "error": {
                    "type": "bot_name_taken",
                } }),
            ),
            SaveBotError::DatabaseError(_e) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                json!({ "error": {
                    "type": "internal_server_error",
                } }),
            ),
            SaveBotError::ValidationFailed(errors) => (
                StatusCode::UNPROCESSABLE_ENTITY,
                json!({ "error": {
                    "type": "validation_failed",
                    "validation_errors": errors,
                } }),
            ),
        };

        let encoded = serde_json::to_vec(&value).expect("could not encode response value");

        Response::builder()
            .status(status)
            .body(body::boxed(body::Full::from(encoded)))
            .expect("could not build response")
    }
}

pub fn validate_bot_name(bot_name: &str) -> Result<(), SaveBotError> {
    let mut errors = Vec::new();

    if bot_name.len() < 3 {
        errors.push("bot name must be at least 3 characters long");
    }

    if bot_name.len() > 32 {
        errors.push("bot name must be at most 32 characters long");
    }

    if !bot_name
        .chars()
        .all(|c| !c.is_uppercase() && (c.is_ascii_alphanumeric() || c == '_' || c == '-'))
    {
        errors.push("only lowercase alphanumeric characters, underscores, and dashes are allowed in bot names");
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(SaveBotError::ValidationFailed(errors))
    }
}

pub async fn save_bot(
    Json(params): Json<SaveBotParams>,
    user: User,
    conn: DatabaseConnection,
) -> Result<Json<Bot>, SaveBotError> {
    let res = bots::find_bot_by_name(&params.bot_name, &conn)
        .optional()
        .expect("could not run query");

    let bot = match res {
        Some(existing_bot) => {
            if existing_bot.owner_id == Some(user.id) {
                existing_bot
            } else {
                return Err(SaveBotError::BotNameTaken);
            }
        }
        None => {
            validate_bot_name(&params.bot_name)?;
            let new_bot = bots::NewBot {
                owner_id: Some(user.id),
                name: &params.bot_name,
            };

            bots::create_bot(&new_bot, &conn).expect("could not create bot")
        }
    };
    let _code_bundle =
        save_code_bundle(&params.code, Some(bot.id), &conn).expect("failed to save code bundle");
    Ok(Json(bot))
}

#[derive(Serialize, Deserialize, Debug)]
pub struct BotParams {
    name: String,
}

pub async fn create_bot(
    conn: DatabaseConnection,
    user: User,
    params: Json<BotParams>,
) -> (StatusCode, Json<Bot>) {
    let bot_params = bots::NewBot {
        owner_id: Some(user.id),
        name: &params.name,
    };
    let bot = bots::create_bot(&bot_params, &conn).unwrap();
    (StatusCode::CREATED, Json(bot))
}

// TODO: handle errors
pub async fn get_bot(
    conn: DatabaseConnection,
    Path(bot_id): Path<i32>,
) -> Result<Json<JsonValue>, StatusCode> {
    let bot = bots::find_bot(bot_id, &conn).map_err(|_| StatusCode::NOT_FOUND)?;
    let bundles = bots::find_bot_code_bundles(bot.id, &conn)
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    Ok(Json(json!({
        "bot": bot,
        "bundles": bundles,
    })))
}

pub async fn get_my_bots(
    conn: DatabaseConnection,
    user: User,
) -> Result<Json<Vec<Bot>>, StatusCode> {
    bots::find_bots_by_owner(user.id, &conn)
        .map(Json)
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}

pub async fn list_bots(conn: DatabaseConnection) -> Result<Json<Vec<Bot>>, StatusCode> {
    bots::find_all_bots(&conn)
        .map(Json)
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}

pub async fn get_ranking(conn: DatabaseConnection) -> Result<Json<Vec<RankedBot>>, StatusCode> {
    ratings::get_bot_ranking(&conn)
        .map(Json)
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}

// TODO: currently this only implements the happy flow
pub async fn upload_code_multipart(
    conn: DatabaseConnection,
    user: User,
    Path(bot_id): Path<i32>,
    mut multipart: Multipart,
) -> Result<Json<CodeBundle>, StatusCode> {
    let bots_dir = PathBuf::from(BOTS_DIR);

    let bot = bots::find_bot(bot_id, &conn).map_err(|_| StatusCode::NOT_FOUND)?;

    if Some(user.id) != bot.owner_id {
        return Err(StatusCode::FORBIDDEN);
    }

    let data = multipart
        .next_field()
        .await
        .map_err(|_| StatusCode::BAD_REQUEST)?
        .ok_or(StatusCode::BAD_REQUEST)?
        .bytes()
        .await
        .map_err(|_| StatusCode::BAD_REQUEST)?;

    // TODO: this random path might be a bit redundant
    let folder_name: String = rand::thread_rng()
        .sample_iter(&Alphanumeric)
        .take(16)
        .map(char::from)
        .collect();

    zip::ZipArchive::new(Cursor::new(data))
        .map_err(|_| StatusCode::BAD_REQUEST)?
        .extract(bots_dir.join(&folder_name))
        .map_err(|_| StatusCode::BAD_REQUEST)?;

    let bundle = bots::NewCodeBundle {
        bot_id: Some(bot.id),
        code_bundle_path: &folder_name,
    };
    let code_bundle =
        bots::create_code_bundle(&bundle, &conn).expect("Failed to create code bundle");

    Ok(Json(code_bundle))
}