atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
ad00e0e051a1e0a7a31f9089046ffa5ced2726bc
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/http/runs.rsRust488 lines14.5 KB
1
//! The resources under `/runs/{id}`.
2
3
use std::{convert::Infallible, fmt::Write as _};
4
5
use axum::{
6
    Json,
7
    body::{Body, Bytes},
8
    http::{StatusCode, header},
9
    response::{IntoResponse, Response},
10
};
11
use serde_json::{Value, json};
12
13
use super::{
14
    ctx::Ctx,
15
    resource::{Resource, Verb},
16
    response::respond,
17
    run::{Greeting, RunResource, Scope},
18
};
19
use crate::{
20
    game::{
21
        Cause, Floor, Grip, Item, LUBRICANTS, Lube, PatchOp, Run, Technique,
22
        balance::{EQ_BAND, MM_PER_INCH},
23
        shaft,
24
    },
25
    headers::ACCEPT_PATCH,
26
    problem::Problem,
27
};
28
29
const fn home(verbs: &'static [Verb<Run>]) -> RunResource {
30
    RunResource {
31
        scope: Scope::Home,
32
        resource: Resource::new(verbs),
33
    }
34
}
35
36
const fn pockets(verbs: &'static [Verb<Run>]) -> RunResource {
37
    RunResource {
38
        scope: Scope::Pockets,
39
        resource: Resource::new(verbs),
40
    }
41
}
42
43
fn not_in_clinic(run: &Run) -> bool {
44
    run.floor != Floor::Clinic
45
}
46
47
fn never(_: &Run) -> bool {
48
    false
49
}
50
51
fn unreachable_handler(_: &mut Run, _: &Ctx) -> Response {
52
    StatusCode::METHOD_NOT_ALLOWED.into_response()
53
}
54
55
pub static RUN: RunResource = RunResource {
56
    scope: Scope::Home,
57
    resource: Resource {
58
        verbs: &[
59
            Verb::new("GET", get_run),
60
            Verb::new("JELQ", jelq)
61
                .only_when(not_in_clinic, "JELQ is not performed in the clinic."),
62
            Verb::new("PUT", put_run),
63
            Verb::new("PATCH", patch_run),
64
            Verb::new("DELETE", delete_run),
65
            Verb::new("TRACE", trace_run),
66
        ],
67
        accept_patch: true,
68
    },
69
};
70
pub static LENGTH: RunResource = home(&[Verb::new("GET", get_length)]);
71
pub static FORESKIN: RunResource = home(&[
72
    Verb::new("GET", get_foreskin),
73
    Verb::new("DELETE", delete_foreskin),
74
]);
75
pub static INVENTORY: RunResource = pockets(&[Verb::new("GET", get_inventory)]);
76
pub static ITEM: RunResource =
77
    pockets(&[Verb::new("GET", get_item), Verb::new("DELETE", delete_item)]);
78
pub static TECHNIQUES: RunResource = home(&[Verb::new("GET", get_techniques)]);
79
pub static DRAWER: RunResource = home(&[Verb::new("POST", search_drawer)]);
80
pub static BRANCH: RunResource = home(&[Verb::new("POST", choose_branch)]);
81
pub static FLOOR: RunResource =
82
    pockets(&[Verb::new("GET", get_floor), Verb::new("POST", leave_floor)]);
83
pub static SHOP: RunResource = home(&[Verb::new("GET", get_shop)]);
84
pub static BUY: RunResource = home(&[Verb::new("POST", buy)]);
85
pub static PORTAL: RunResource = pockets(&[
86
    Verb::new("GET", get_portal),
87
    Verb::new("POST", accept_portal),
88
]);
89
pub static ELDER: RunResource = home(&[Verb::new("GET", get_elder)]);
90
pub static GRIP: RunResource = home(&[Verb::new("GET", get_grip)]);
91
pub static DIAGNOSIS: RunResource = pockets(&[Verb::new("GET", get_diagnosis)]);
92
pub static FOOTAGE: RunResource = pockets(&[
93
    Verb::new("GET", get_footage),
94
    Verb::new("DELETE", unreachable_handler).only_when(
95
        never,
96
        "The footage has been cached by intermediaries. It cannot be deleted.",
97
    ),
98
]);
99
100
fn get_run(run: &mut Run, ctx: &Ctx) -> Response {
101
    if ctx
102
        .header(header::ACCEPT)
103
        .is_some_and(|accept| accept.contains("reassurance"))
104
    {
105
        return Problem::new(
106
            StatusCode::NOT_ACCEPTABLE,
107
            "no-reassurance",
108
            "The server does not produce reassurance.",
109
        )
110
        .into_response();
111
    }
112
    (
113
        StatusCode::OK,
114
        [(header::ETAG, run.etag())],
115
        Json(run.view()),
116
    )
117
        .into_response()
118
}
119
120
fn parse_techniques(run: &Run, ctx: &Ctx) -> Result<Vec<Technique>, Problem> {
121
    let required = || {
122
        Problem::new(
123
            StatusCode::BAD_REQUEST,
124
            "technique-required",
125
            "No technique was specified.",
126
        )
127
        .with("techniques", run.path("/techniques"))
128
    };
129
    let names = ctx
130
        .query("technique")
131
        .filter(|n| !n.trim().is_empty())
132
        .ok_or_else(required)?;
133
    names
134
        .split(',')
135
        .map(str::trim)
136
        .filter(|n| !n.is_empty())
137
        .map(|name| {
138
            Technique::parse(name).ok_or_else(|| {
139
                Problem::new(
140
                    StatusCode::BAD_REQUEST,
141
                    "unknown-technique",
142
                    format!("{name} is not a technique."),
143
                )
144
                .with("techniques", run.path("/techniques"))
145
            })
146
        })
147
        .collect()
148
}
149
150
fn parse_intensity(ctx: &Ctx) -> Result<i32, Problem> {
151
    match ctx.query("intensity").map(str::parse::<i32>) {
152
        None => Ok(5),
153
        Some(Ok(i)) if (1..=10).contains(&i) => Ok(i),
154
        Some(_) => Err(Problem::new(
155
            StatusCode::BAD_REQUEST,
156
            "intensity-out-of-range",
157
            "Intensity is measured from 1 to 10.",
158
        )),
159
    }
160
}
161
162
fn jelq(run: &mut Run, ctx: &Ctx) -> Response {
163
    let parsed = parse_techniques(run, ctx).and_then(|techniques| {
164
        let intensity = parse_intensity(ctx)?;
165
        let lube = Lube::from_content_type(ctx.header(header::CONTENT_TYPE))?;
166
        Ok((techniques, intensity, lube))
167
    });
168
    match parsed {
169
        Ok((techniques, intensity, lube)) => {
170
            respond(run.jelq(&techniques, intensity, lube, ctx.now))
171
        }
172
        Err(problem) => problem.into_response(),
173
    }
174
}
175
176
fn put_run(run: &mut Run, _: &Ctx) -> Response {
177
    run.put().into_response()
178
}
179
180
fn patch_run(run: &mut Run, ctx: &Ctx) -> Response {
181
    let is_patch = ctx
182
        .header(header::CONTENT_TYPE)
183
        .is_some_and(|ct| ct.starts_with("application/json-patch+json"));
184
    if !is_patch {
185
        return Problem::new(
186
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
187
            "patch-format",
188
            "Patches are accepted as application/json-patch+json.",
189
        )
190
        .header(ACCEPT_PATCH, "application/json-patch+json")
191
        .into_response();
192
    }
193
    match serde_json::from_slice::<Vec<PatchOp>>(&ctx.body) {
194
        Ok(ops) => respond(run.patch(&ops)),
195
        Err(_) => Problem::new(
196
            StatusCode::BAD_REQUEST,
197
            "malformed-patch",
198
            "The patch could not be parsed.",
199
        )
200
        .into_response(),
201
    }
202
}
203
204
fn delete_run(run: &mut Run, _: &Ctx) -> Response {
205
    run.end(Cause::Abandoned);
206
    StatusCode::NO_CONTENT.into_response()
207
}
208
209
fn trace_run(run: &mut Run, ctx: &Ctx) -> Response {
210
    run.shame += 1;
211
    let mut message = format!("{} {} {:?}\r\n", ctx.method, ctx.uri, ctx.version);
212
    for (name, value) in &ctx.headers {
213
        let _ = write!(
214
            message,
215
            "{name}: {}\r\n",
216
            value.to_str().unwrap_or("<binary>")
217
        );
218
    }
219
    message.push_str("\r\n");
220
    (
221
        StatusCode::OK,
222
        [(header::CONTENT_TYPE, "message/http")],
223
        message,
224
    )
225
        .into_response()
226
}
227
228
fn millimetres(inches: f64) -> usize {
229
    (inches * MM_PER_INCH).round() as usize
230
}
231
232
fn parse_inch_range(range: &str, total: f64) -> Option<(f64, f64)> {
233
    let (start, end) = range.strip_prefix("inches=")?.split_once('-')?;
234
    let start: f64 = start.trim().parse().ok()?;
235
    let end: f64 = match end.trim() {
236
        "" => total,
237
        end => end.parse().ok()?,
238
    };
239
    (start >= 0.0 && start < total && start <= end).then_some((start, end.min(total)))
240
}
241
242
fn get_length(run: &mut Run, ctx: &Ctx) -> Response {
243
    let inches = if run.items.ruler {
244
        run.current_length()
245
    } else {
246
        run.self_reported()
247
    };
248
    let body = shaft(millimetres(inches));
249
    let content_type = (
250
        header::CONTENT_TYPE,
251
        "text/plain; charset=us-ascii".to_owned(),
252
    );
253
    let accept_ranges = (header::ACCEPT_RANGES, "inches".to_owned());
254
255
    if let Some(range) = ctx.header(header::RANGE)
256
        && range.starts_with("inches=")
257
    {
258
        let Some((start, end)) = parse_inch_range(range, inches) else {
259
            return Problem::new(
260
                StatusCode::RANGE_NOT_SATISFIABLE,
261
                "range-not-satisfiable",
262
                format!("The requested range is not available. {inches:.2} inches are."),
263
            )
264
            .header(header::CONTENT_RANGE, format!("inches */{inches:.2}"))
265
            .into_response();
266
        };
267
        let from = millimetres(start).min(body.len() - 1);
268
        let to = millimetres(end).clamp(from + 1, body.len());
269
        let content_range = (
270
            header::CONTENT_RANGE,
271
            format!("inches {start:.2}-{end:.2}/{inches:.2}"),
272
        );
273
        return (
274
            StatusCode::PARTIAL_CONTENT,
275
            [content_type, accept_ranges, content_range],
276
            body[from..to].to_owned(),
277
        )
278
            .into_response();
279
    }
280
281
    if run.items.ruler {
282
        return (StatusCode::OK, [content_type, accept_ranges], body).into_response();
283
    }
284
    let chunks: Vec<Result<Bytes, Infallible>> = body
285
        .into_bytes()
286
        .chunks(16)
287
        .map(|c| Ok(Bytes::copy_from_slice(c)))
288
        .collect();
289
    let body = Body::from_stream(futures_util::stream::iter(chunks));
290
    (StatusCode::OK, [content_type, accept_ranges], body).into_response()
291
}
292
293
fn get_foreskin(run: &mut Run, _: &Ctx) -> Response {
294
    if run.foreskin.is_none() {
295
        return Problem::new(
296
            StatusCode::GONE,
297
            "foreskin-gone",
298
            "The foreskin is gone. It will not be returning.",
299
        )
300
        .into_response();
301
    }
302
    (StatusCode::NO_CONTENT, [(header::ETAG, run.etag())]).into_response()
303
}
304
305
fn delete_foreskin(run: &mut Run, ctx: &Ctx) -> Response {
306
    respond(run.delete_foreskin(ctx.header(header::IF_MATCH)))
307
}
308
309
fn get_inventory(run: &mut Run, _: &Ctx) -> Response {
310
    let items: Vec<Value> = run
311
        .items
312
        .owned()
313
        .into_iter()
314
        .map(|item| {
315
            json!({
316
                "name": item.slug(),
317
                "href": run.path(&format!("/inventory/{}", item.slug())),
318
            })
319
        })
320
        .collect();
321
    Json(json!({
322
        "items": items,
323
        "ice_packs": run.items.ice_packs,
324
        "supplements": run.items.supplements,
325
        "excuses": run.excuses(),
326
    }))
327
    .into_response()
328
}
329
330
fn owned_item(run: &Run, ctx: &Ctx) -> Result<Item, Problem> {
331
    Item::parse(ctx.param("item"))
332
        .filter(|&item| run.items.has(item))
333
        .ok_or_else(|| {
334
            Problem::new(
335
                StatusCode::NOT_FOUND,
336
                "no-such-item",
337
                "You do not have that.",
338
            )
339
        })
340
}
341
342
fn get_item(run: &mut Run, ctx: &Ctx) -> Response {
343
    match owned_item(run, ctx) {
344
        Ok(item) => {
345
            Json(json!({ "name": item.slug(), "description": item.description() })).into_response()
346
        }
347
        Err(problem) => problem.into_response(),
348
    }
349
}
350
351
fn delete_item(run: &mut Run, ctx: &Ctx) -> Response {
352
    match owned_item(run, ctx) {
353
        Ok(item) => respond(run.drop_item(item)),
354
        Err(problem) => problem.into_response(),
355
    }
356
}
357
358
fn get_techniques(run: &mut Run, _: &Ctx) -> Response {
359
    let listed: Vec<Value> = Technique::ALL
360
        .into_iter()
361
        .map(|t| t.describe(run.forum_read()))
362
        .collect();
363
    Json(json!({
364
        "usage": format!("JELQ {}?technique=<name>[,<name>]&intensity=<1-10>", run.path("")),
365
        "lubricant": "Declared with Content-Type.",
366
        "lubricants": LUBRICANTS,
367
        "eq_band": [EQ_BAND.start(), EQ_BAND.end()],
368
        "techniques": listed,
369
    }))
370
    .into_response()
371
}
372
373
fn search_drawer(run: &mut Run, _: &Ctx) -> Response {
374
    respond(run.search_drawer())
375
}
376
377
fn choose_branch(run: &mut Run, ctx: &Ctx) -> Response {
378
    respond(run.choose(ctx.param("choice")))
379
}
380
381
fn get_floor(run: &mut Run, _: &Ctx) -> Response {
382
    Json(run.floor_view()).into_response()
383
}
384
385
fn leave_floor(run: &mut Run, _: &Ctx) -> Response {
386
    respond(run.advance())
387
}
388
389
fn get_shop(run: &mut Run, _: &Ctx) -> Response {
390
    respond(run.shop_view().map(Json))
391
}
392
393
fn buy(run: &mut Run, ctx: &Ctx) -> Response {
394
    respond(run.buy(ctx.param("item")))
395
}
396
397
fn get_portal(run: &mut Run, _: &Ctx) -> Response {
398
    Json(json!({
399
        "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.",
400
        "accept": { "href": run.path("/portal"), "method": "POST" },
401
    }))
402
    .into_response()
403
}
404
405
fn accept_portal(run: &mut Run, _: &Ctx) -> Response {
406
    respond(run.accept_terms())
407
}
408
409
fn get_elder(run: &mut Run, ctx: &Ctx) -> Response {
410
    respond(run.elder(
411
        ctx.header(header::PROXY_AUTHORIZATION),
412
        ctx.header(header::IF_MODIFIED_SINCE),
413
    ))
414
}
415
416
fn requested_grip(ctx: &Ctx) -> Option<Grip> {
417
    let connection = ctx.header(header::CONNECTION)?.to_ascii_lowercase();
418
    if !connection.split(',').any(|token| token.trim() == "upgrade") {
419
        return None;
420
    }
421
    ctx.header(header::UPGRADE)?
422
        .split(',')
423
        .find_map(|protocol| Grip::parse(protocol.trim()))
424
}
425
426
fn get_grip(run: &mut Run, ctx: &Ctx) -> Response {
427
    if let Some(grip) = requested_grip(ctx) {
428
        run.set_grip(grip);
429
        let mut response = (
430
            StatusCode::SWITCHING_PROTOCOLS,
431
            [
432
                (header::UPGRADE, grip.name()),
433
                (header::CONNECTION, "upgrade"),
434
            ],
435
        )
436
            .into_response();
437
        response.extensions_mut().insert(Greeting(format!(
438
            "You are now jelqing {}.\r\n",
439
            grip.name()
440
        )));
441
        return response;
442
    }
443
    let detail = match ctx.header(header::UPGRADE) {
444
        Some(protocol) => {
445
            format!("The server does not know the {protocol} grip. Grips are protocols.")
446
        }
447
        None => "Grips are protocols. Change grip by upgrading the connection.".to_owned(),
448
    };
449
    (
450
        StatusCode::OK,
451
        [(header::UPGRADE, "overhand, underhand")],
452
        Json(json!({ "grip": run.grip.name(), "detail": detail })),
453
    )
454
        .into_response()
455
}
456
457
fn get_diagnosis(run: &mut Run, ctx: &Ctx) -> Response {
458
    respond(run.diagnose(
459
        ctx.header(header::AUTHORIZATION),
460
        ctx.header(header::IF_NONE_MATCH),
461
    ))
462
}
463
464
fn get_footage(run: &mut Run, _: &Ctx) -> Response {
465
    let Some((filmed, age)) = run.footage() else {
466
        return Problem::new(
467
            StatusCode::NOT_FOUND,
468
            "no-footage",
469
            "There is no footage. Yet.",
470
        )
471
        .into_response();
472
    };
473
    (
474
        [
475
            (
476
                header::CACHE_CONTROL,
477
                "public, max-age=31536000, immutable".to_owned(),
478
            ),
479
            (header::AGE, age.to_string()),
480
            (header::LAST_MODIFIED, httpdate::fmt_http_date(filmed)),
481
        ],
482
        Json(json!({
483
            "detail": "A recording. It is grainy. It is unmistakably you. It has been shared.",
484
            "views": 1 + age * 37,
485
        })),
486
    )
487
        .into_response()
488
}