-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathblogs.rs
More file actions
532 lines (488 loc) · 16.1 KB
/
blogs.rs
File metadata and controls
532 lines (488 loc) · 16.1 KB
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use activitypub::collection::OrderedCollection;
use atom_syndication::{Entry, FeedBuilder};
use diesel::SaveChangesDsl;
use rocket::{
http::{ContentType, Status},
request::LenientForm,
response::{content::Content, Flash, Redirect},
State,
};
use rocket_i18n::I18n;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use std::{borrow::Cow, collections::HashMap};
use validator::{Validate, ValidationError, ValidationErrors};
use plume_common::activity_pub::{ActivityStream, ApRequest};
use plume_common::utils;
use plume_models::{
blog_authors::*, blogs::*, instance::Instance, medias::*, posts::Post, safe_string::SafeString,
users::User, Connection, PlumeRocket,
};
use reqwest::Client;
use routes::{errors::ErrorPage, Page, RespondOrRedirect};
use template_utils::{IntoContext, Ructe};
fn detail_guts(
blog: Blog,
page: Option<Page>,
rockets: PlumeRocket,
) -> Result<RespondOrRedirect, ErrorPage> {
let page = page.unwrap_or_default();
let conn = &*rockets.conn;
let posts = Post::blog_page(conn, &blog, page.limits())?;
let articles_count = Post::count_for_blog(conn, &blog)?;
let authors = &blog.list_authors(conn)?;
Ok(render!(blogs::details(
&rockets.to_context(),
blog,
authors,
page.0,
Page::total(articles_count as i32),
posts
))
.into())
}
#[get("/~/<name>?<page>", rank = 2)]
pub fn details(
name: String,
page: Option<Page>,
rockets: PlumeRocket,
) -> Result<RespondOrRedirect, ErrorPage> {
let blog = Blog::find_by_fqn(&rockets, &name)?;
// check this first, and return early
// doing this prevents partially moving `blog` into the `match (tuple)`,
// which makes it impossible to reuse then.
if blog.custom_domain == None {
return detail_guts(blog, page, rockets);
}
match (blog.custom_domain, page) {
(Some(ref custom_domain), Some(ref page)) => {
Ok(Redirect::to(format!("https://{}/?page={}", custom_domain, page)).into())
}
(Some(ref custom_domain), _) => {
Ok(Redirect::to(format!("https://{}/", custom_domain)).into())
}
// we need this match arm, or the match won't compile
(None, _) => unreachable!("This code path should have already been handled!"),
}
}
pub fn activity_detail_guts(
blog: Blog,
rockets: PlumeRocket,
_ap: ApRequest,
) -> Option<ActivityStream<CustomGroup>> {
Some(ActivityStream::new(blog.to_activity(&*rockets.conn).ok()?))
}
#[get("/~/<name>", rank = 1)]
pub fn activity_details(
name: String,
rockets: PlumeRocket,
_ap: ApRequest,
) -> Option<ActivityStream<CustomGroup>> {
let blog = Blog::find_by_fqn(&rockets, &name).ok()?;
activity_detail_guts(blog, rockets, _ap)
}
#[get("/blogs/new")]
pub fn new(rockets: PlumeRocket, _user: User) -> Ructe {
render!(blogs::new(
&rockets.to_context(),
&NewBlogForm::default(),
ValidationErrors::default()
))
}
// mounted as /domain_validation/
#[get("/<validation_id>")]
pub fn domain_validation(
validation_id: String,
valid_domains: State<Mutex<HashMap<String, Instant>>>,
) -> Status {
let mutex = valid_domains.inner().lock();
let mut validation_map = mutex.unwrap();
let validation_getter = validation_map.clone();
let value = validation_getter.get(&validation_id);
if value.is_none() {
// validation id not found
return Status::NotFound;
}
// we have valid id, now check the time
let valid_until = value.unwrap();
let now = Instant::now();
// nope, expired (410: gone)
if now.duration_since(*valid_until).as_secs() > 0 {
validation_map.remove(&validation_id);
// validation expired
return Status::Gone;
}
validation_map.remove(&validation_id);
Status::Ok
}
pub mod custom {
use plume_common::activity_pub::{ActivityStream, ApRequest};
use plume_models::{blogs::Blog, blogs::CustomGroup, blogs::Host, PlumeRocket};
use rocket::{http::Status, State};
use routes::{errors::ErrorPage, Page, RespondOrRedirect};
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::Instant;
#[get("/<custom_domain>?<page>", rank = 2)]
pub fn details(
custom_domain: String,
page: Option<Page>,
rockets: PlumeRocket,
) -> Result<RespondOrRedirect, ErrorPage> {
let blog = Blog::find_by_host(&rockets, Host::new(custom_domain))?;
super::detail_guts(blog, page, rockets)
}
#[get("/<custom_domain>", rank = 1)]
pub fn activity_details(
custom_domain: String,
rockets: PlumeRocket,
_ap: ApRequest,
) -> Option<ActivityStream<CustomGroup>> {
let blog = Blog::find_by_host(&rockets, Host::new(custom_domain)).ok()?;
super::activity_detail_guts(blog, rockets, _ap)
}
// mounted as /custom_domains/domain_validation/
#[get("/<validation_id>")]
pub fn domain_validation(
validation_id: String,
valid_domains: State<Mutex<HashMap<String, Instant>>>,
) -> Status {
super::domain_validation(validation_id, valid_domains)
}
}
#[get("/blogs/new", rank = 2)]
pub fn new_auth(i18n: I18n) -> Flash<Redirect> {
utils::requires_login(
&i18n!(
i18n.catalog,
"To create a new blog, you need to be logged in"
),
uri!(new),
)
}
#[derive(Default, FromForm, Validate)]
pub struct NewBlogForm {
#[validate(custom(function = "valid_slug", message = "Invalid name"))]
pub title: String,
pub custom_domain: String,
}
fn valid_slug(title: &str) -> Result<(), ValidationError> {
let slug = utils::make_actor_id(title);
if slug.is_empty() {
Err(ValidationError::new("empty_slug"))
} else {
Ok(())
}
}
fn valid_domain(domain: &str, valid_domains: State<Mutex<HashMap<String, Instant>>>) -> bool {
let mutex = valid_domains.inner().lock();
let mut validation_map = mutex.unwrap();
let random_id = utils::random_hex();
validation_map.insert(
random_id.clone(),
Instant::now().checked_add(Duration::new(60, 0)).unwrap(),
);
let client = Client::new();
let validation_uri = format!("https://{}/domain_validation/{}", domain, random_id);
match client.get(&validation_uri).send() {
Ok(resp) => resp.status().is_success(),
Err(_) => false,
}
}
#[post("/blogs/new", data = "<form>")]
pub fn create(
form: LenientForm<NewBlogForm>,
rockets: PlumeRocket,
valid_domains: State<Mutex<HashMap<String, Instant>>>,
) -> RespondOrRedirect {
let slug = utils::make_actor_id(&form.title);
let conn = &*rockets.conn;
let intl = &rockets.intl.catalog;
let user = rockets.user.clone().unwrap();
let (custom_domain, dns_ok) = if form.custom_domain.is_empty() {
(None, true)
} else {
let dns_check = valid_domain(&form.custom_domain.clone(), valid_domains);
(Some(Host::new(form.custom_domain.clone())), dns_check)
};
let mut errors = match form.validate() {
Ok(_) => ValidationErrors::new(),
Err(e) => e,
};
if Blog::find_by_fqn(&rockets, &slug).is_ok() {
errors.add(
"title",
ValidationError {
code: Cow::from("existing_slug"),
message: Some(Cow::from(i18n!(
intl,
"A blog with the same name already exists."
))),
params: HashMap::new(),
},
);
}
if !errors.is_empty() {
return render!(blogs::new(&rockets.to_context(), &*form, errors)).into();
}
let blog = Blog::insert(
&*conn,
NewBlog::new_local(
slug.clone(),
form.title.to_string(),
String::from(""),
Instance::get_local()
.expect("blog::create: instance error")
.id,
custom_domain,
)
.expect("blog::create: new local error"),
)
.expect("blog::create: error");
BlogAuthor::insert(
&*conn,
NewBlogAuthor {
blog_id: blog.id,
author_id: user.id,
is_owner: true,
},
)
.expect("blog::create: author error");
if dns_ok {
Flash::success(
Redirect::to(uri!(details: name = slug.clone(), page = _)),
&i18n!(intl, "Your blog was successfully created!"),
)
.into()
} else {
Flash::warning(
Redirect::to(uri!(details: name = slug.clone(), page = _)),
&i18n!(intl, "Your blog was successfully created, but the custom domain seems invalid. Please check it is correct from your blog's settings."),
)
.into()
}
}
#[post("/~/<name>/delete")]
pub fn delete(name: String, rockets: PlumeRocket) -> RespondOrRedirect {
let conn = &*rockets.conn;
let blog = Blog::find_by_fqn(&rockets, &name).expect("blog::delete: blog not found");
if rockets
.user
.clone()
.and_then(|u| u.is_author_in(&*conn, &blog).ok())
.unwrap_or(false)
{
blog.delete(&conn, &rockets.searcher)
.expect("blog::expect: deletion error");
Flash::success(
Redirect::to(uri!(super::instance::index)),
i18n!(rockets.intl.catalog, "Your blog was deleted."),
)
.into()
} else {
// TODO actually return 403 error code
render!(errors::not_authorized(
&rockets.to_context(),
i18n!(
rockets.intl.catalog,
"You are not allowed to delete this blog."
)
))
.into()
}
}
#[derive(FromForm, Validate)]
pub struct EditForm {
#[validate(custom(function = "valid_slug", message = "Invalid name"))]
pub title: String,
pub summary: String,
pub icon: Option<i32>,
pub banner: Option<i32>,
pub custom_domain: String,
}
#[get("/~/<name>/edit")]
pub fn edit(name: String, rockets: PlumeRocket) -> Result<Ructe, ErrorPage> {
let conn = &*rockets.conn;
let blog = Blog::find_by_fqn(&rockets, &name)?;
if rockets
.user
.clone()
.and_then(|u| u.is_author_in(conn, &blog).ok())
.unwrap_or(false)
{
let user = rockets
.user
.clone()
.expect("blogs::edit: User was None while it shouldn't");
let medias = Media::for_user(conn, user.id).expect("Couldn't list media");
let custom_domain = match blog.custom_domain {
Some(ref c) => c.to_string(),
_ => String::from(""),
};
Ok(render!(blogs::edit(
&rockets.to_context(),
&blog,
medias,
&EditForm {
title: blog.title.clone(),
summary: blog.summary.clone(),
icon: blog.icon_id,
banner: blog.banner_id,
custom_domain: custom_domain,
},
ValidationErrors::default()
)))
} else {
// TODO actually return 403 error code
Ok(render!(errors::not_authorized(
&rockets.to_context(),
i18n!(
rockets.intl.catalog,
"You are not allowed to edit this blog."
)
)))
}
}
/// Returns true if the media is owned by `user` and is a picture
fn check_media(conn: &Connection, id: i32, user: &User) -> bool {
if let Ok(media) = Media::get(conn, id) {
media.owner_id == user.id && media.category() == MediaCategory::Image
} else {
false
}
}
#[put("/~/<name>/edit", data = "<form>")]
pub fn update(
name: String,
form: LenientForm<EditForm>,
rockets: PlumeRocket,
) -> RespondOrRedirect {
let conn = &*rockets.conn;
let intl = &rockets.intl.catalog;
let mut blog = Blog::find_by_fqn(&rockets, &name).expect("blog::update: blog not found");
if !rockets
.user
.clone()
.and_then(|u| u.is_author_in(&*conn, &blog).ok())
.unwrap_or(false)
{
// TODO actually return 403 error code
return render!(errors::not_authorized(
&rockets.to_context(),
i18n!(
rockets.intl.catalog,
"You are not allowed to edit this blog."
)
))
.into();
}
let user = rockets
.user
.clone()
.expect("blogs::edit: User was None while it shouldn't");
form.validate()
.and_then(|_| {
if let Some(icon) = form.icon {
if !check_media(&*conn, icon, &user) {
let mut errors = ValidationErrors::new();
errors.add(
"",
ValidationError {
code: Cow::from("icon"),
message: Some(Cow::from(i18n!(
intl,
"You can't use this media as a blog icon."
))),
params: HashMap::new(),
},
);
return Err(errors);
}
}
if let Some(banner) = form.banner {
if !check_media(&*conn, banner, &user) {
let mut errors = ValidationErrors::new();
errors.add(
"",
ValidationError {
code: Cow::from("banner"),
message: Some(Cow::from(i18n!(
intl,
"You can't use this media as a blog banner."
))),
params: HashMap::new(),
},
);
return Err(errors);
}
}
blog.title = form.title.clone();
blog.summary = form.summary.clone();
blog.summary_html = SafeString::new(
&utils::md_to_html(
&form.summary,
None,
true,
Some(Media::get_media_processor(
&conn,
blog.list_authors(&conn)
.expect("Couldn't get list of authors")
.iter()
.collect(),
)),
)
.0,
);
blog.icon_id = form.icon;
blog.banner_id = form.banner;
if !form.custom_domain.is_empty() {
blog.custom_domain = Some(Host::new(form.custom_domain.clone()))
}
blog.save_changes::<Blog>(&*conn)
.expect("Couldn't save blog changes");
Ok(Flash::success(
Redirect::to(uri!(details: name = name, page = _)),
i18n!(intl, "Your blog information have been updated."),
))
})
.map_err(|err| {
let medias = Media::for_user(&*conn, user.id).expect("Couldn't list media");
render!(blogs::edit(
&rockets.to_context(),
&blog,
medias,
&*form,
err
))
})
.unwrap()
.into()
}
#[get("/~/<name>/outbox")]
pub fn outbox(name: String, rockets: PlumeRocket) -> Option<ActivityStream<OrderedCollection>> {
let blog = Blog::find_by_fqn(&rockets, &name).ok()?;
Some(blog.outbox(&*rockets.conn).ok()?)
}
#[get("/~/<name>/atom.xml")]
pub fn atom_feed(name: String, rockets: PlumeRocket) -> Option<Content<String>> {
let blog = Blog::find_by_fqn(&rockets, &name).ok()?;
let conn = &*rockets.conn;
let feed = FeedBuilder::default()
.title(blog.title.clone())
.id(Instance::get_local()
.ok()?
.compute_box("~", &name, "atom.xml"))
.entries(
Post::get_recents_for_blog(&*conn, &blog, 15)
.ok()?
.into_iter()
.map(|p| super::post_to_atom(p, &*conn))
.collect::<Vec<Entry>>(),
)
.build()
.ok()?;
Some(Content(
ContentType::new("application", "atom+xml"),
feed.to_string(),
))
}