~boringcactus/gemifedi

ref: d39391002bd8c63b47d8f6190cca70c51eb56a7b gemifedi/src/main.rs -rw-r--r-- 16.1 KiB
d3939100 — Melody Horn use gemtext 0.2.0 1 year, 2 months ago
                                                                                
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use std::{
    fs::{self, File, create_dir_all},
    iter,
    io::BufReader,
    path::PathBuf,
    sync::Arc,
};

use elefren::{
    prelude::*,
    helpers::toml as mastodon_toml,
};
use maj::{
    gemini as gemtext,
    Response as GeminiResponse,
    server::{
        Handler as GeminiHandler,
        Request as GeminiRequest,
        Error,
    },
    route, split, seg,
};
use rustls::ServerConfig;

mod client_cert_fix;
use client_cert_fix::TrustAnyClientCertOrAnonymous;

mod html2gemtext;

mod gemini_util;
use gemini_util::*;
mod mastodon_util;
use mastodon_util::*;

fn undo_prefix(did: Option<bool>) -> &'static str {
    if did.unwrap_or(false) {
        "un"
    } else {
        ""
    }
}

fn render_post(post: elefren::entities::status::Status, highlight: bool) -> Vec<gemtext::Node> {
    let reply_info = match post.in_reply_to_account_id {
        Some(account) => {
            let replyee = if account == post.account.id {
                post.account.display_name.clone()
            } else {
                post.mentions.iter()
                    .find_map(|mention| {
                        if mention.id == account {
                            Some(mention.acct.clone())
                        } else {
                            None
                        }
                    })
                    .unwrap_or("someone they untagged".to_string())
            };
            format!(", replying to {}", replyee)
        },
        None => format!("")
    };

    let reblog_info = match post.reblog {
        Some(status) => format!(", reblogging {}", status.account.display_name),
        None => format!("")
    };

    let post_info = format!(
        "{account_name}{reply_info}{reblog_info}:",
        account_name=post.account.display_name,
        reply_info=reply_info,
        reblog_info=reblog_info,
    );

    let heading_level = if highlight {
        2
    } else {
        3
    };
    let detail_link = if highlight { post.url } else { None }.unwrap_or(format!("/status/{}", post.id));
    let mut result = vec![
        gemtext::Node::Heading { level: heading_level, body: post_info },
    ];

    let post_actions = if highlight {
        gemtext::Builder::new()
            .link("?reply", Some("reply".to_string()))
            .link("?boost", Some(format!("{}boost", undo_prefix(post.reblogged))))
            .link("?fav", Some(format!("{}favorite", undo_prefix(post.favourited))))
            .build()
    } else {
        vec![]
    };

    result.extend(strip_html(&post.content));
    result.push(gemtext::Node::Link { to: detail_link, name: None });
    result.extend(post_actions);
    result.push(gemtext::Node::blank());
    result
}

fn mastodon_data_path(req: &GeminiRequest) -> Option<PathBuf> {
    let mut result = PathBuf::from("data");
    result.push("users");
    let hash = req.cert_hash()?;
    result.push(hash);
    Some(result.with_extension("toml"))
}

struct Handler;

impl Default for Handler {
    fn default() -> Self {
        Handler {}
    }
}

impl Handler {
    fn home(&self, req: GeminiRequest) -> Result<GeminiResponse, Error> {
        let path = mastodon_data_path(&req);
        let path = match path {
            Some(path) => path,
            None => return Ok(GeminiResponse::need_cert("Need a cert to be able to log in!"))
        };
        let mastodon = match mastodon_toml::from_file(path) {
            Ok(data) => Mastodon::from(data),
            Err(_) => return Ok(temp_redirect("/auth"))
        };

        let home = mastodon.get_home_timeline().unwrap();

        let before_timeline = gemtext::Builder::new()
            .link("/post", Some("write a new post".to_string()))
            .text("")
            .heading(1, "your timeline")
            .build();

        let posts = home.items_iter()
            .take(10)
            .flat_map(|post| render_post(post, false));

        let body = before_timeline.into_iter()
            .chain(posts)
            .collect::<Vec<_>>();

        Ok(GeminiResponse::render(apply_global_template(body)))
    }

    fn post(&self, req: GeminiRequest) -> Result<GeminiResponse, Error> {
        let path = mastodon_data_path(&req);
        let path = match path {
            Some(path) => path,
            None => return Ok(GeminiResponse::need_cert("Need a cert to be able to log in!"))
        };
        let mastodon = match mastodon_toml::from_file(path) {
            Ok(data) => Mastodon::from(data),
            Err(_) => return Ok(temp_redirect("/auth"))
        };
        match req.url.query() {
            Some(post) => {
                let post = percent_encoding::percent_decode_str(post).decode_utf8_lossy();
                let new_status = StatusBuilder::new()
                    .status(post)
                    .build()
                    .unwrap();
                let status = mastodon.new_status(new_status).unwrap();
                Ok(temp_redirect(format!("/status/{}", status.id)))
            }
            None => {
                Ok(GeminiResponse::input(format!("Post some text")))
            }
        }
    }

    fn auth_begin(&self, req: GeminiRequest) -> Result<GeminiResponse, Error> {
        match req.url.query() {
            Some(instance) => {
                assert!(url::Host::parse(instance).is_ok(), "got a bad instance domain name");
                let mut target = req.url.clone();
                target.set_query(None);
                target.path_segments_mut().unwrap().push(instance);
                Ok(temp_redirect(target.to_string()))
            }
            None => {
                Ok(GeminiResponse::input("Enter the domain of your instance (e.g. \"mastodon.social\")"))
            }
        }
    }

    fn auth_continue(&self, req: GeminiRequest, instance: &str) -> Result<GeminiResponse, Error> {
        let app_install = get_app_install(instance);

        let mut ready_for_code_url = req.url.clone();
        ready_for_code_url.path_segments_mut().unwrap().push("code");
        let response = gemtext::Builder::new()
            .link(app_install.authorize_url().unwrap(), Some("Open this HTTP link to get an authorization code from your instance".to_string()))
            .link(ready_for_code_url.into_string(), Some("Click this Gemini link to enter that authorization code here".to_string()))
            .build();
        return Ok(GeminiResponse::render(response));
    }

    fn auth_finish(&self, req: GeminiRequest, instance: &str) -> Result<GeminiResponse, Error> {
        let app_install = get_app_install(instance);
        let code = match req.url.query() {
            Some(code) => code,
            None => {
                return Ok(GeminiResponse::input("Enter the authorization code you got"));
            }
        };

        let mastodon = app_install.complete(code).unwrap();

        // Save app data for using on the next run.
        let path = mastodon_data_path(&req);
        let path = match path {
            Some(path) => path,
            None => return Ok(GeminiResponse::need_cert("Need a cert to be able to log in!"))
        };
        path.parent().and_then(|parent| create_dir_all(parent).ok());
        mastodon_toml::to_file(&*mastodon, path).unwrap();

        let mut destination = req.url.clone();
        destination.path_segments_mut().unwrap().clear();
        destination.set_query(None);
        Ok(temp_redirect(destination.to_string()))
    }

    fn status(&self, req: GeminiRequest, id: &str) -> Result<GeminiResponse, Error> {
        let path = mastodon_data_path(&req);
        let path = match path {
            Some(path) => path,
            None => return Ok(GeminiResponse::need_cert("Need a cert to be able to log in!"))
        };
        let mastodon = match mastodon_toml::from_file(path) {
            Ok(data) => Mastodon::from(data),
            Err(_) => return Ok(temp_redirect("/auth"))
        };

        let status = mastodon.get_status(id);
        let context = mastodon.get_context(id);
        let (status, context) = match (status, context) {
            (Ok(status), Ok(context)) => (status, context),
            _ => return Ok(GeminiResponse::not_found()),
        };

        match req.url.query() {
            Some("reply") => {
                return Ok(temp_redirect(format!("/status/{}/reply", id)));
            }
            Some("boost") => {
                let action = if status.reblogged.unwrap_or(false) {
                    mastodon.unreblog(id)
                } else {
                    mastodon.reblog(id)
                };
                action.unwrap();
                return Ok(temp_redirect(format!("/status/{}", id)));
            }
            Some("fav") => {
                let action = if status.favourited.unwrap_or(false) {
                    mastodon.unfavourite(id)
                } else {
                    mastodon.favourite(id)
                };
                action.unwrap();
                return Ok(temp_redirect(format!("/status/{}", id)));
            }
            _ => {}
        }

        let posts = context.ancestors.into_iter()
            .chain(iter::once(status))
            .chain(context.descendants)
            .flat_map(|post| {
                let highlight = post.id == id;
                render_post(post, highlight)
            })
            .collect();

        Ok(GeminiResponse::render(apply_global_template(posts)))
    }

    fn reply(&self, req: GeminiRequest, id: &str) -> Result<GeminiResponse, Error> {
        let path = mastodon_data_path(&req);
        let path = match path {
            Some(path) => path,
            None => return Ok(GeminiResponse::need_cert("Need a cert to be able to log in!"))
        };
        let mastodon = match mastodon_toml::from_file(path) {
            Ok(data) => Mastodon::from(data),
            Err(_) => return Ok(temp_redirect("/auth"))
        };
        match req.url.query() {
            Some(post) => {
                let post = percent_encoding::percent_decode_str(post).decode_utf8_lossy();
                let new_status = StatusBuilder::new()
                    .status(post)
                    .in_reply_to(id)
                    .build()
                    .unwrap();
                let status = mastodon.new_status(new_status).unwrap();
                Ok(temp_redirect(format!("/status/{}", status.id)))
            }
            None => {
                Ok(GeminiResponse::input(format!("Reply with some text")))
            }
        }
    }

    fn about(&self, _req: GeminiRequest) -> Result<GeminiResponse, Error> {
        let response = gemtext::parse(concat!(r#"# About gemifedi v"#, env!("CARGO_PKG_VERSION"), r#"

gemifedi is a Mastodon / Pleroma client for the Gemini protocol. it uses the OAuth API to access your timeline, and stores data keyed by your chosen client certificate. i recommend hosting it yourself instead of trusting someone else to host it for you.

=> https://git.sr.ht/~boringcactus/gemifedi source code and hosting instructions
=> /                                        log in on this install of gemifedi
"#));

        Ok(GeminiResponse::render(response))
    }

    fn logout(&self, req: GeminiRequest) -> Result<GeminiResponse, Error> {
        let path = mastodon_data_path(&req);
        let path = match path {
            Some(path) => path,
            None => return Ok(GeminiResponse::need_cert("Need a cert to be able to log in!"))
        };
        if path.exists() {
            fs::remove_file(path).unwrap();
        }
        Ok(GeminiResponse::gemini(b"Logged out successfully\n=> /about about gemifedi".to_vec()))
    }
}

#[async_trait::async_trait]
impl GeminiHandler for Handler {
    async fn handle(&self, req: GeminiRequest) -> Result<GeminiResponse, Error> {
        let path = req.url.path().to_string();
        route!(path, {
            (/)                         => self.home(req);
            (/"post")                   => self.post(req);
            (/"auth")                   => self.auth_begin(req);
            (/"auth"/[instance])        => self.auth_continue(req, instance);
            (/"auth"/[instance]/"code") => self.auth_finish(req, instance);
            (/"logout")                 => self.logout(req);
            (/"status"/[id])            => self.status(req, id);
            (/"status"/[id]/"reply")    => self.reply(req, id);
            (/"about")                  => self.about(req);
        });
        Ok(GeminiResponse::not_found())
    }
}

use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[structopt(author, about)]
struct Opt {
    /// Path to TLS certificate (will attempt to generate if not found, defaults to ./<domain>.cert)
    #[structopt(short, long, parse(from_os_str))]
    cert: Option<PathBuf>,

    /// Path to TLS key (will attempt to generate if not found, defaults to ./<domain>.key)
    #[structopt(short, long, parse(from_os_str))]
    key: Option<PathBuf>,

    /// Domain name (e.g. `localhost`, `gemifedi.example.net`)
    #[structopt()]
    domain: String,

    /// Port number to run on
    #[structopt(default_value = "1965")]
    port: u16,
}

#[async_std::main]
async fn main() -> Result<(), Error> {
    pretty_env_logger::formatted_builder()
        .filter(None, log::LevelFilter::Info)
        .filter(Some("gemifedi"), log::LevelFilter::max())
        .init();

    let options: Opt = Opt::from_args();

    if let Err(error) = url::Host::parse(&options.domain) {
        eprintln!("{:?} is not a valid hostname", options.domain);
        return Err(Box::new(error));
    }

    let key_file = options.key.unwrap_or(PathBuf::from(format!("./{}.key", options.domain)));

    if !key_file.exists() {
        log::info!("couldn't find key file {}, generating", key_file.display());
        use std::process::Command;
        let genrsa = Command::new("openssl")
            .args(&["genrsa", "-out"])
            .arg(&key_file)
            .arg("2048")
            .output();
        match genrsa {
            Err(err) => {
                eprintln!("Failed to generate key file");
                return Err(Box::new(err));
            }
            Ok(output) if !output.status.success() => {
                eprintln!("Error generating key file");
                return Err(format!("{:#?}", output).into());
            }
            _ => {
                log::debug!("generated key file OK")
            }
        }
    }

    let cert_file = options.cert.unwrap_or(PathBuf::from(format!("./{}.cert", options.domain)));

    if !cert_file.exists() {
        log::info!("couldn't find certificate file {}, generating", cert_file.display());
        let mut temp_file = tempfile::NamedTempFile::new()?;
        use std::io::Write;
        writeln!(temp_file, "[req]\ndistinguished_name=req\n[SAN]\nsubjectAltName=DNS:{}", options.domain)?;
        use std::process::Command;
        let req = Command::new("openssl")
            .args(&["req", "-new", "-x509", "-key"])
            .arg(&key_file)
            .arg("-out")
            .arg(&cert_file)
            .args(&["-days", "3650", "-subj"])
            .arg(format!("/CN={}", options.domain))
            .args(&["-extensions", "SAN", "-config"])
            .arg(temp_file.path())
            .output();
        match req {
            Err(err) => {
                eprintln!("Failed to generate certificate file");
                return Err(Box::new(err));
            }
            Ok(output) if !output.status.success() => {
                eprintln!("Error generating certificate file");
                return Err(format!("{:#?}", output).into());
            }
            _ => {
                log::debug!("generated certificate file OK")
            }
        }
    }

    let mut tls_config = ServerConfig::new(TrustAnyClientCertOrAnonymous::new());
    let mut cert_file = BufReader::new(File::open(cert_file)?);
    let mut key_file = BufReader::new(File::open(key_file)?);
    let keys = rustls::internal::pemfile::rsa_private_keys(&mut key_file).unwrap();
    let key = keys.into_iter().next().unwrap();
    tls_config.set_single_cert(
        rustls::internal::pemfile::certs(&mut cert_file).unwrap(),
        key,
    )?;

    log::info!("about to start listening on gemini://{}{}/", options.domain, if options.port == 1965 { format!("") } else { format!(":{}", options.port) });

    maj::server::serve(
        Arc::new(Handler::default()),
        tls_config,
        options.domain,
        options.port,
    ).await
}