atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
aef6f6498ea2ef0c39d1079a0ca0bc99afdd9bac
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/game/forum.rsRust322 lines11.7 KB
1
use std::{sync::LazyLock, time::SystemTime};
2
3
use axum::http::{StatusCode, header};
4
use serde_json::{Value, json};
5
6
use super::{
7
    Cause, Floor, Outcome, Run,
8
    balance::{EXAGGERATION, MEDITATION_ODDS, PATIENCE, THREAD_READS, ULI_ODDS},
9
    credentials::{Scheme, parse_credentials},
10
    measure::{exaggeration, honest},
11
};
12
use crate::{headers::X_FORUM_NOTE, problem::Problem};
13
14
pub const FORUM_THREAD: &str = "/forum/threads/2009";
15
pub const ELDER_LAST_MODIFIED: &str = "Sun, 14 Jun 2009 03:12:00 GMT";
16
static ELDER_POSTED: LazyLock<SystemTime> = LazyLock::new(|| {
17
    httpdate::parse_http_date(ELDER_LAST_MODIFIED).expect("the Elder's date is a valid HTTP-date")
18
});
19
20
const SPREADSHEET: &str = "\
21
date,length,girth,technique,notes,honest?
22
2007-01-03,7.50,5.50,wet,baseline,no
23
2007-06-11,7.50,5.50,wet,feeling fuller,no
24
2008-01-02,7.50,5.50,dry,new routine,no
25
2008-09-19,7.50,5.50,uli,PUT is idempotent. do not use PUT.,no
26
2009-06-14,7.50,5.50,wet,progress is slow but real,no
27
";
28
29
fn nothing_new() -> Outcome {
30
    Outcome::empty(StatusCode::NOT_MODIFIED).header(
31
        header::WARNING,
32
        r#"199 - "Nothing new has been posted since 2009.""#,
33
    )
34
}
35
36
pub fn forum_thread() -> Value {
37
    json!({
38
        "title": "The definitive jelqing FAQ (updated 2009)",
39
        "posts": [
40
            { "author": "TheElder", "body": "Warm up. Always warm up. A cold jelq is a 412 waiting to happen." },
41
            { "author": "TheElder", "body": "Keep EQ between 50 and 70. Above 70 you are gambling. Above 90 you are a cautionary tale." },
42
            { "author": "newbie_2009", "body": "everyone keeps saying uli. who is uli" },
43
            { "author": "TheElder", "body": "uli was a member here. He posted the technique in 2001 and never posted again. Some say he ascended. The search function says his account is gone." },
44
            { "author": "TheElder", "body": "We do not say his name in vain. We say it in girth." },
45
            { "author": "newbie_2009", "body": "I have been sending PUT for three weeks and nothing has changed." },
46
            { "author": "TheElder", "body": "PUT is idempotent. Read the spec." },
47
            { "author": "TheElder", "body": "Members verify with a Ruler. Proxy-Authorization, inches, no rounding up. We can tell." },
48
            { "author": "throwaway_77", "body": "my doctor said i was normal. i didnt believe him. i still dont know what he meant by bearer" },
49
            { "author": "TheElder", "body": "My numbers are in my spreadsheet. They have not changed since 2009. Nothing about me has changed since 2009." },
50
        ],
51
    })
52
}
53
54
fn verification(detail: &str) -> Problem {
55
    Problem::new(
56
        StatusCode::PROXY_AUTHENTICATION_REQUIRED,
57
        "verification-required",
58
        detail,
59
    )
60
    .header(header::PROXY_AUTHENTICATE, "Ruler realm=\"forum\"")
61
}
62
63
/// The browser tab that opens on turn 10.
64
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
65
pub enum Story {
66
    Unopened,
67
    Pending,
68
    ReadForum,
69
    ClosedTab,
70
}
71
72
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
73
pub enum Branch {
74
    Forum,
75
    CloseTab,
76
}
77
78
impl Branch {
79
    pub fn slug(self) -> &'static str {
80
        match self {
81
            Self::Forum => "forum",
82
            Self::CloseTab => "close-tab",
83
        }
84
    }
85
}
86
87
impl std::str::FromStr for Branch {
88
    type Err = ();
89
90
    fn from_str(slug: &str) -> Result<Self, ()> {
91
        [Self::Forum, Self::CloseTab]
92
            .into_iter()
93
            .find(|branch| branch.slug() == slug)
94
            .ok_or(())
95
    }
96
}
97
98
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
99
pub enum Elder {
100
    Unverified { strikes: u8 },
101
    Verified,
102
    Beaten,
103
}
104
105
/// The run's life online, from the tab on turn 10 to the footage the neighbour took.
106
pub struct Online {
107
    pub(crate) story: Story,
108
    pub(crate) meditation_taught: bool,
109
    pub(crate) uli_taught: bool,
110
    pub(crate) elder: Elder,
111
    pub(crate) filmed_at: Option<SystemTime>,
112
}
113
114
impl Default for Online {
115
    fn default() -> Self {
116
        Self {
117
            story: Story::Unopened,
118
            meditation_taught: false,
119
            uli_taught: false,
120
            elder: Elder::Unverified { strikes: 0 },
121
            filmed_at: None,
122
        }
123
    }
124
}
125
126
impl Run {
127
    pub(super) fn branch_offer(&self) -> Outcome {
128
        let forum = self.path(&format!("/branches/{}", Branch::Forum.slug()));
129
        let close = self.path(&format!("/branches/{}", Branch::CloseTab.slug()));
130
        Outcome::json(
131
            StatusCode::MULTIPLE_CHOICES,
132
            json!({
133
                "detail": "A browser tab is open. It has been open for some time.",
134
                "choices": [
135
                    { "href": forum, "method": "POST", "title": "Read the forum" },
136
                    { "href": close, "method": "POST", "title": "Close the tab" },
137
                ],
138
            }),
139
        )
140
        .header(
141
            header::LINK,
142
            format!(
143
                "<{forum}>; rel=\"alternate\"; title=\"Read the forum\"; allow=\"POST\", <{close}>; rel=\"alternate\"; title=\"Close the tab\"; allow=\"POST\""
144
            ),
145
        )
146
    }
147
148
    pub fn choose(&mut self, choice: Branch) -> Result<Outcome, Problem> {
149
        if self.online.story != Story::Pending {
150
            return Err(Problem::new(
151
                StatusCode::CONFLICT,
152
                "no-decision-pending",
153
                "There is no decision pending.",
154
            ));
155
        }
156
        let (story, location, detail) = match choice {
157
            Branch::Forum => {
158
                self.standing.shame += 3;
159
                let detail = if self.learn_meditation() {
160
                    "The thread is from 2009. A technique called uli is discussed at length. Further down, someone explains how to breathe, and you write it down."
161
                } else {
162
                    "The thread is from 2009. A technique called uli is discussed at length."
163
                };
164
                (Story::ReadForum, self.path("/techniques"), detail)
165
            }
166
            Branch::CloseTab => {
167
                self.standing.suspicion = 0;
168
                (
169
                    Story::ClosedTab,
170
                    self.path(""),
171
                    "The tab is closed. Nobody saw it.",
172
                )
173
            }
174
        };
175
        self.online.story = story;
176
        self.touch();
177
        Ok(
178
            Outcome::json(StatusCode::SEE_OTHER, json!({ "detail": detail }))
179
                .header(header::LOCATION, location),
180
        )
181
    }
182
183
    /// Re-reading is free. Each floor gets a couple of live reads that may surface the reply,
184
    /// after which the forum is down and the browser serves what it kept.
185
    pub fn read_thread(&mut self) -> Result<Outcome, Problem> {
186
        if self.online.story == Story::Pending {
187
            return Ok(self.branch_offer());
188
        }
189
        if !self.thread_reachable() {
190
            return Err(Problem::new(
191
                StatusCode::NOT_FOUND,
192
                "no-thread",
193
                "There is no thread to re-read. Nobody has mentioned a forum yet.",
194
            ));
195
        }
196
        self.end_kitchen_visit();
197
        if self.online.uli_taught {
198
            return Ok(Outcome::json(StatusCode::OK, forum_thread()));
199
        }
200
        if self.here.thread_rolls >= THREAD_READS {
201
            let age = SystemTime::now()
202
                .duration_since(*ELDER_POSTED)
203
                .map_or(0, |age| age.as_secs());
204
            return Ok(Outcome::json(StatusCode::OK, forum_thread())
205
                .header(header::AGE, age.to_string())
206
                .header(header::WARNING, r#"112 - "Disconnected operation""#));
207
        }
208
        self.here.thread_rolls += 1;
209
        self.touch();
210
        let detail = if !self.online.meditation_taught {
211
            if !self.learn_meditation() {
212
                return Ok(nothing_new());
213
            }
214
            "Between two arguments about pumps, a reply explains how to breathe. In through the nose, out through the mouth. You write it down."
215
        } else {
216
            if !self.chance(
217
                self.decision(
218
                    "teach-uli",
219
                    "Does this reread finally surface the 2009 reply that teaches uli?",
220
                ),
221
                ULI_ODDS,
222
            ) {
223
                return Ok(nothing_new());
224
            }
225
            self.online.uli_taught = true;
226
            "Past the necroposting, a reply from TheElder lays out the technique. Uli. The full routine. You write it down before the tab can lose it."
227
        };
228
        Ok(Outcome::json(StatusCode::OK, json!({ "detail": detail }))
229
            .header(header::LOCATION, self.path("/techniques")))
230
    }
231
232
    fn learn_meditation(&mut self) -> bool {
233
        let taught = self.chance(
234
            self.decision(
235
                "teach-meditation",
236
                "Does the thread surface the reply that teaches the breathing technique?",
237
            ),
238
            MEDITATION_ODDS,
239
        );
240
        self.online.meditation_taught |= taught;
241
        taught
242
    }
243
244
    fn elder_strike(&mut self, problem: Problem) -> Problem {
245
        self.touch();
246
        let Elder::Unverified { strikes } = &mut self.online.elder else {
247
            return problem;
248
        };
249
        *strikes += 1;
250
        if *strikes < PATIENCE {
251
            return problem;
252
        }
253
        self.end(Cause::Banned)
254
    }
255
256
    /// Failed verification counts toward a ban even on GET, the way repeated bad credentials lock an account.
257
    fn verify_member(&mut self, proxy_authorization: Option<&str>) -> Result<(), Problem> {
258
        if !matches!(self.online.elder, Elder::Unverified { .. }) {
259
            return Ok(());
260
        }
261
        let Some(credentials) = proxy_authorization else {
262
            return Err(verification("The forum requires verification."));
263
        };
264
        let Some(claimed) =
265
            parse_credentials(credentials, Scheme::Ruler).and_then(|v| v.parse::<f64>().ok())
266
        else {
267
            return Err(verification("The forum requires verification, in inches."));
268
        };
269
        let actual = self.current_length();
270
        if claimed >= actual + EXAGGERATION {
271
            self.standing.shame += 2;
272
            return Err(self.elder_strike(exaggeration()));
273
        }
274
        if !honest(claimed, actual) {
275
            self.standing.shame += 1;
276
            let failed = verification("Verification failed. The forum can tell.");
277
            if self.girth_respected() {
278
                return Err(failed.header(
279
                    X_FORUM_NOTE,
280
                    "The mods have let this one go. Girth is also a dimension.",
281
                ));
282
            }
283
            return Err(self.elder_strike(failed));
284
        }
285
        self.online.elder = Elder::Verified;
286
        self.touch();
287
        Ok(())
288
    }
289
290
    pub fn elder(
291
        &mut self,
292
        proxy_authorization: Option<&str>,
293
        if_modified_since: Option<&str>,
294
    ) -> Result<Outcome, Problem> {
295
        if self.floor != Floor::Forum {
296
            return Err(Problem::new(
297
                StatusCode::NOT_FOUND,
298
                "elder-absent",
299
                "The Elder only posts on the forum.",
300
            ));
301
        }
302
        self.verify_member(proxy_authorization)?;
303
304
        let current = if_modified_since
305
            .and_then(|d| httpdate::parse_http_date(d).ok())
306
            .is_some_and(|since| since >= *ELDER_POSTED);
307
        if current {
308
            if self.online.elder != Elder::Beaten {
309
                self.online.elder = Elder::Beaten;
310
                self.touch();
311
            }
312
            return Ok(Outcome::empty(StatusCode::NOT_MODIFIED)
313
                .header(header::LAST_MODIFIED, ELDER_LAST_MODIFIED));
314
        }
315
        let spreadsheet = Outcome::raw(StatusCode::OK, "text/csv; header=present", SPREADSHEET)
316
            .header(header::LAST_MODIFIED, ELDER_LAST_MODIFIED);
317
        if self.online.filmed_at.is_some() {
318
            return Ok(spreadsheet.header(X_FORUM_NOTE, "We have seen the footage."));
319
        }
320
        Ok(spreadsheet)
321
    }
322
}