atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
2176d9a94bd9f6eaed0b8222251bd637ca2fb4a7
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/http/runs.rsRust302 lines9.0 KB
1
//! The resources under `/runs/{id}`.
2
3
use axum::{
4
    Json,
5
    http::{StatusCode, header},
6
    response::{IntoResponse, Response},
7
};
8
use serde_json::{Value, json};
9
10
use super::{
11
    ctx::Ctx,
12
    inventory::{delete_item, get_inventory, get_item},
13
    parse::{parse_intensity, parse_techniques},
14
    resource::{Resource, Verb},
15
    response::respond,
16
    run::{Greeting, RunResource, Scope},
17
    shaft::{get_foreskin, get_length},
18
};
19
use crate::{
20
    game::{
21
        Branch, Cause, Floor, Grip, Item, LUBRICANTS, Lube, Run, Technique,
22
        balance::VIEWS_PER_SECOND,
23
    },
24
    problem::Problem,
25
};
26
27
const fn home(verbs: &'static [Verb<Run>]) -> RunResource {
28
    RunResource {
29
        scope: Scope::Home,
30
        resource: Resource::new(verbs),
31
    }
32
}
33
34
const fn pockets(verbs: &'static [Verb<Run>]) -> RunResource {
35
    RunResource {
36
        scope: Scope::Pockets,
37
        resource: Resource::new(verbs),
38
    }
39
}
40
41
fn not_in_clinic(run: &Run) -> bool {
42
    run.floor != Floor::Clinic
43
}
44
45
pub static RUN: RunResource = RunResource {
46
    scope: Scope::Home,
47
    resource: Resource::new(&[
48
        Verb::new("GET", get_run),
49
        Verb::new("JELQ", jelq).only_when(not_in_clinic, "JELQ is not performed in the clinic."),
50
        Verb::new("HOLD", hold_run).only_when(
51
            Run::can_hold,
52
            "HOLD is only available once Swollen or at 2 stamina or less.",
53
        ),
54
        Verb::new("PUT", put_run),
55
        Verb::new("DELETE", delete_run),
56
        Verb::new("TRACE", trace_run),
57
    ]),
58
};
59
pub static LENGTH: RunResource = home(&[Verb::new("GET", get_length)]);
60
pub static FORESKIN: RunResource = home(&[
61
    Verb::new("GET", get_foreskin),
62
    Verb::new("DELETE", delete_foreskin),
63
]);
64
pub static INVENTORY: RunResource = pockets(&[Verb::new("GET", get_inventory)]);
65
pub static ITEM: RunResource =
66
    pockets(&[Verb::new("GET", get_item), Verb::new("DELETE", delete_item)]);
67
pub static TECHNIQUES: RunResource = home(&[Verb::new("GET", get_techniques)]);
68
pub static DRAWER: RunResource = home(&[Verb::new("POST", search_drawer)]);
69
pub static BRANCH: RunResource = home(&[Verb::new("POST", choose_branch)]);
70
pub static KITCHEN: RunResource = home(&[Verb::new("POST", raid_kitchen)]);
71
pub static MELON: RunResource = home(&[Verb::new("POST", commit_melon)]);
72
pub static THREAD: RunResource = pockets(&[Verb::new("GET", get_thread)]);
73
pub static FLOOR: RunResource =
74
    home(&[Verb::new("GET", get_floor), Verb::new("POST", leave_floor)]);
75
pub static SHOP: RunResource = home(&[Verb::new("GET", get_shop)]);
76
pub static BUY: RunResource = home(&[Verb::new("POST", buy)]);
77
pub static PORTAL: RunResource = pockets(&[
78
    Verb::new("GET", get_portal),
79
    Verb::new("POST", accept_portal),
80
]);
81
pub static ELDER: RunResource = home(&[Verb::new("GET", get_elder)]);
82
pub static GRIP: RunResource = home(&[Verb::new("GET", get_grip)]);
83
pub static DIAGNOSIS: RunResource = pockets(&[Verb::new("GET", get_diagnosis)]);
84
pub static FOOTAGE: RunResource = pockets(&[
85
    Verb::new("GET", get_footage),
86
    Verb::refused(
87
        "DELETE",
88
        "The footage has been cached by intermediaries. It cannot be deleted.",
89
    ),
90
]);
91
92
fn get_run(run: &mut Run, ctx: &Ctx) -> Response {
93
    if ctx
94
        .header(header::ACCEPT)
95
        .is_some_and(|accept| accept.contains("reassurance"))
96
    {
97
        return Problem::new(
98
            StatusCode::NOT_ACCEPTABLE,
99
            "no-reassurance",
100
            "The server does not produce reassurance.",
101
        )
102
        .into_response();
103
    }
104
    (
105
        StatusCode::OK,
106
        [(header::ETAG, run.etag())],
107
        Json(run.view()),
108
    )
109
        .into_response()
110
}
111
112
fn jelq(run: &mut Run, ctx: &Ctx) -> Response {
113
    let parsed = parse_techniques(run, ctx).and_then(|techniques| {
114
        let intensity = parse_intensity(ctx)?;
115
        let lube = Lube::from_content_type(ctx.header(header::CONTENT_TYPE))?;
116
        Ok((techniques, intensity, lube))
117
    });
118
    match parsed {
119
        Ok((techniques, intensity, lube)) => respond(run.jelq(&techniques, intensity, lube)),
120
        Err(problem) => problem.into_response(),
121
    }
122
}
123
124
fn put_run(run: &mut Run, _: &Ctx) -> Response {
125
    run.put().into_response()
126
}
127
128
fn hold_run(run: &mut Run, _: &Ctx) -> Response {
129
    respond(run.hold())
130
}
131
132
fn delete_run(run: &mut Run, _: &Ctx) -> Response {
133
    run.end(Cause::Abandoned);
134
    StatusCode::NO_CONTENT.into_response()
135
}
136
137
fn trace_run(run: &mut Run, ctx: &Ctx) -> Response {
138
    run.trace();
139
    (
140
        StatusCode::OK,
141
        [(header::CONTENT_TYPE, "message/http")],
142
        ctx.echo(),
143
    )
144
        .into_response()
145
}
146
147
fn delete_foreskin(run: &mut Run, ctx: &Ctx) -> Response {
148
    respond(run.delete_foreskin(ctx.header(header::IF_MATCH)))
149
}
150
151
fn get_techniques(run: &mut Run, _: &Ctx) -> Response {
152
    let listed: Vec<Value> = Technique::ALL
153
        .into_iter()
154
        .map(|t| t.describe(run.knows(t)))
155
        .collect();
156
    Json(json!({
157
        "usage": format!("JELQ {}?technique=<name>[,<name>]&intensity=<1-10>", run.path("")),
158
        "lubricant": "Declared with Content-Type.",
159
        "lubricants": LUBRICANTS,
160
        "techniques": listed,
161
    }))
162
    .into_response()
163
}
164
165
fn search_drawer(run: &mut Run, _: &Ctx) -> Response {
166
    respond(run.search_drawer())
167
}
168
169
fn choose_branch(run: &mut Run, ctx: &Ctx) -> Response {
170
    match ctx.param("choice").parse::<Branch>() {
171
        Ok(choice) => respond(run.choose(choice)),
172
        Err(()) => Problem::new(
173
            StatusCode::NOT_FOUND,
174
            "no-such-choice",
175
            "That was not one of the choices.",
176
        )
177
        .into_response(),
178
    }
179
}
180
181
fn get_floor(run: &mut Run, _: &Ctx) -> Response {
182
    Json(run.floor_view()).into_response()
183
}
184
185
fn leave_floor(run: &mut Run, _: &Ctx) -> Response {
186
    respond(run.advance())
187
}
188
189
fn get_shop(run: &mut Run, _: &Ctx) -> Response {
190
    respond(run.browse_shop().map(Json))
191
}
192
193
fn buy(run: &mut Run, ctx: &Ctx) -> Response {
194
    respond(run.buy(Item::parse(ctx.param("item"))))
195
}
196
197
fn raid_kitchen(run: &mut Run, _: &Ctx) -> Response {
198
    respond(run.raid_kitchen())
199
}
200
201
fn commit_melon(run: &mut Run, _: &Ctx) -> Response {
202
    respond(run.commit_melon())
203
}
204
205
fn get_thread(run: &mut Run, _: &Ctx) -> Response {
206
    respond(run.read_thread())
207
}
208
209
fn get_portal(run: &mut Run, _: &Ctx) -> Response {
210
    Json(json!({
211
        "terms": "By connecting you agree that the hotel is not responsible for anything that happens in this room, and that it does not want to know.",
212
        "accept": { "href": run.path("/portal"), "method": "POST" },
213
    }))
214
    .into_response()
215
}
216
217
fn accept_portal(run: &mut Run, _: &Ctx) -> Response {
218
    respond(run.accept_terms())
219
}
220
221
fn get_elder(run: &mut Run, ctx: &Ctx) -> Response {
222
    respond(run.elder(
223
        ctx.header(header::PROXY_AUTHORIZATION),
224
        ctx.header(header::IF_MODIFIED_SINCE),
225
    ))
226
}
227
228
fn requested_grip(ctx: &Ctx) -> Option<Grip> {
229
    let connection = ctx.header(header::CONNECTION)?.to_ascii_lowercase();
230
    if !connection.split(',').any(|token| token.trim() == "upgrade") {
231
        return None;
232
    }
233
    ctx.header(header::UPGRADE)?
234
        .split(',')
235
        .find_map(|protocol| protocol.trim().parse::<Grip>().ok())
236
}
237
238
fn get_grip(run: &mut Run, ctx: &Ctx) -> Response {
239
    if let Some(grip) = requested_grip(ctx) {
240
        if let Err(problem) = run.set_grip(grip) {
241
            return problem.into_response();
242
        }
243
        let mut response = (
244
            StatusCode::SWITCHING_PROTOCOLS,
245
            [
246
                (header::UPGRADE, grip.name()),
247
                (header::CONNECTION, "upgrade"),
248
            ],
249
        )
250
            .into_response();
251
        response.extensions_mut().insert(Greeting(format!(
252
            "You are now jelqing {}.\r\n",
253
            grip.name()
254
        )));
255
        return response;
256
    }
257
    let detail = match ctx.header(header::UPGRADE) {
258
        Some(protocol) => {
259
            format!("The server does not know the {protocol} grip. Grips are protocols.")
260
        }
261
        None => "Grips are protocols. Change grip by upgrading the connection.".to_owned(),
262
    };
263
    (
264
        StatusCode::OK,
265
        [(header::UPGRADE, "overhand, underhand")],
266
        Json(json!({ "grip": run.grip().name(), "detail": detail })),
267
    )
268
        .into_response()
269
}
270
271
fn get_diagnosis(run: &mut Run, ctx: &Ctx) -> Response {
272
    respond(run.diagnose(
273
        ctx.header(header::AUTHORIZATION),
274
        ctx.header(header::IF_NONE_MATCH),
275
    ))
276
}
277
278
fn get_footage(run: &mut Run, _: &Ctx) -> Response {
279
    let Some((filmed, age)) = run.footage() else {
280
        return Problem::new(
281
            StatusCode::NOT_FOUND,
282
            "no-footage",
283
            "There is no footage. Yet.",
284
        )
285
        .into_response();
286
    };
287
    (
288
        [
289
            (
290
                header::CACHE_CONTROL,
291
                "public, max-age=31536000, immutable".to_owned(),
292
            ),
293
            (header::AGE, age.to_string()),
294
            (header::LAST_MODIFIED, httpdate::fmt_http_date(filmed)),
295
        ],
296
        Json(json!({
297
            "detail": "A recording. It is grainy. It is unmistakably you. It has been shared.",
298
            "views": 1 + age * VIEWS_PER_SECOND,
299
        })),
300
    )
301
        .into_response()
302
}