atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
8ab6a1382c4c997e5e0544c2af62018ca376c78b
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/game/forum.rsRust322 lines11.6 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 thread(detail: Option<&str>) -> Outcome {
30
    let mut body = forum_thread();
31
    if let Some(detail) = detail {
32
        body["detail"] = json!(detail);
33
    }
34
    Outcome::json(StatusCode::OK, body).header(header::LAST_MODIFIED, ELDER_LAST_MODIFIED)
35
}
36
37
pub fn forum_thread() -> Value {
38
    json!({
39
        "title": "The definitive jelqing FAQ (updated 2009)",
40
        "posts": [
41
            { "author": "TheElder", "body": "Warm up. Always warm up. A cold jelq is a 412 waiting to happen." },
42
            { "author": "TheElder", "body": "Keep EQ between 50 and 70. Above 70 you are gambling. Above 90 you are a cautionary tale." },
43
            { "author": "newbie_2009", "body": "everyone keeps saying uli. who is uli" },
44
            { "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." },
45
            { "author": "TheElder", "body": "We do not say his name in vain. We say it in girth." },
46
            { "author": "newbie_2009", "body": "I have been sending PUT for three weeks and nothing has changed." },
47
            { "author": "TheElder", "body": "PUT is idempotent. Read the spec." },
48
            { "author": "TheElder", "body": "Members verify with a Ruler. Proxy-Authorization, inches, no rounding up. We can tell." },
49
            { "author": "throwaway_77", "body": "my doctor said i was normal. i didnt believe him. i still dont know what he meant by bearer" },
50
            { "author": "TheElder", "body": "My numbers are in my spreadsheet. They have not changed since 2009. Nothing about me has changed since 2009." },
51
        ],
52
    })
53
}
54
55
fn verification(detail: &str) -> Problem {
56
    Problem::new(
57
        StatusCode::PROXY_AUTHENTICATION_REQUIRED,
58
        "verification-required",
59
        detail,
60
    )
61
    .header(header::PROXY_AUTHENTICATE, "Ruler realm=\"forum\"")
62
}
63
64
/// The browser tab that opens on turn 10.
65
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
66
pub enum Story {
67
    Unopened,
68
    Pending,
69
    ReadForum,
70
    ClosedTab,
71
}
72
73
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
74
pub enum Branch {
75
    Forum,
76
    CloseTab,
77
}
78
79
impl Branch {
80
    pub fn slug(self) -> &'static str {
81
        match self {
82
            Self::Forum => "forum",
83
            Self::CloseTab => "close-tab",
84
        }
85
    }
86
}
87
88
impl std::str::FromStr for Branch {
89
    type Err = ();
90
91
    fn from_str(slug: &str) -> Result<Self, ()> {
92
        [Self::Forum, Self::CloseTab]
93
            .into_iter()
94
            .find(|branch| branch.slug() == slug)
95
            .ok_or(())
96
    }
97
}
98
99
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
100
pub enum Elder {
101
    Unverified { strikes: u8 },
102
    Verified,
103
    Beaten,
104
}
105
106
/// The run's life online, from the tab on turn 10 to the footage the neighbour took.
107
pub struct Online {
108
    pub(crate) story: Story,
109
    pub(crate) meditation_taught: bool,
110
    pub(crate) uli_taught: bool,
111
    pub(crate) elder: Elder,
112
    pub(crate) filmed_at: Option<SystemTime>,
113
}
114
115
impl Default for Online {
116
    fn default() -> Self {
117
        Self {
118
            story: Story::Unopened,
119
            meditation_taught: false,
120
            uli_taught: false,
121
            elder: Elder::Unverified { strikes: 0 },
122
            filmed_at: None,
123
        }
124
    }
125
}
126
127
impl Run {
128
    pub(super) fn branch_offer(&self) -> Outcome {
129
        let forum = self.path(&format!("/branches/{}", Branch::Forum.slug()));
130
        let close = self.path(&format!("/branches/{}", Branch::CloseTab.slug()));
131
        Outcome::json(
132
            StatusCode::MULTIPLE_CHOICES,
133
            json!({
134
                "detail": "A browser tab is open. It has been open for some time.",
135
                "choices": [
136
                    { "href": forum, "method": "POST", "title": "Read the forum" },
137
                    { "href": close, "method": "POST", "title": "Close the tab" },
138
                ],
139
            }),
140
        )
141
        .header(
142
            header::LINK,
143
            format!(
144
                "<{forum}>; rel=\"alternate\"; title=\"Read the forum\"; allow=\"POST\", <{close}>; rel=\"alternate\"; title=\"Close the tab\"; allow=\"POST\""
145
            ),
146
        )
147
    }
148
149
    pub fn choose(&mut self, choice: Branch) -> Result<Outcome, Problem> {
150
        if self.online.story != Story::Pending {
151
            return Err(Problem::new(
152
                StatusCode::CONFLICT,
153
                "no-decision-pending",
154
                "There is no decision pending.",
155
            ));
156
        }
157
        let (story, location, detail) = match choice {
158
            Branch::Forum => {
159
                self.standing.shame += 3;
160
                let detail = if self.learn_meditation() {
161
                    "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."
162
                } else {
163
                    "The thread is from 2009. A technique called uli is discussed at length."
164
                };
165
                (Story::ReadForum, self.path("/techniques"), detail)
166
            }
167
            Branch::CloseTab => {
168
                self.standing.suspicion = 0;
169
                (
170
                    Story::ClosedTab,
171
                    self.path(""),
172
                    "The tab is closed. Nobody saw it.",
173
                )
174
            }
175
        };
176
        self.online.story = story;
177
        self.touch();
178
        Ok(
179
            Outcome::json(StatusCode::SEE_OTHER, json!({ "detail": detail }))
180
                .header(header::LOCATION, location),
181
        )
182
    }
183
184
    /// Re-reading is free. Each floor gets a couple of live reads that may surface the reply,
185
    /// after which the forum is down and the browser serves what it kept.
186
    pub fn read_thread(&mut self) -> Result<Outcome, Problem> {
187
        if !self.thread_reachable() {
188
            return Err(Problem::new(
189
                StatusCode::NOT_FOUND,
190
                "no-thread",
191
                "There is no thread. Nobody has mentioned a forum yet.",
192
            ));
193
        }
194
        if self.online.story == Story::Pending {
195
            return Ok(thread(None));
196
        }
197
        self.end_kitchen_visit();
198
        if self.online.uli_taught {
199
            return Ok(thread(None));
200
        }
201
        if self.here.thread_rolls >= THREAD_READS {
202
            let age = SystemTime::now()
203
                .duration_since(*ELDER_POSTED)
204
                .map_or(0, |age| age.as_secs());
205
            return Ok(thread(None)
206
                .header(header::AGE, age.to_string())
207
                .header(header::WARNING, r#"112 - "Disconnected operation""#));
208
        }
209
        self.here.thread_rolls += 1;
210
        self.touch();
211
        let detail = if !self.online.meditation_taught {
212
            if !self.learn_meditation() {
213
                return Ok(thread(None));
214
            }
215
            "Between two arguments about pumps, a reply explains how to breathe. In through the nose, out through the mouth. You write it down."
216
        } else {
217
            if !self.chance(
218
                self.decision(
219
                    "teach-uli",
220
                    "Does this read finally surface the 2009 reply that teaches uli?",
221
                ),
222
                ULI_ODDS,
223
            ) {
224
                return Ok(thread(None));
225
            }
226
            self.online.uli_taught = true;
227
            "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."
228
        };
229
        Ok(thread(Some(detail)))
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
}