2021-01-06 15:04:49 +13:00
|
|
|
// CRATES
|
2021-02-10 06:38:52 +13:00
|
|
|
use crate::utils::{prefs, template, Preferences};
|
2021-01-06 15:04:49 +13:00
|
|
|
use askama::Template;
|
2021-02-10 06:38:52 +13:00
|
|
|
use tide::{http::Cookie, Request, Response};
|
2021-01-06 15:04:49 +13:00
|
|
|
use time::{Duration, OffsetDateTime};
|
|
|
|
|
|
|
|
// STRUCTS
|
|
|
|
#[derive(Template)]
|
2021-01-08 05:38:05 +13:00
|
|
|
#[template(path = "settings.html")]
|
2021-01-06 15:04:49 +13:00
|
|
|
struct SettingsTemplate {
|
2021-01-09 14:50:03 +13:00
|
|
|
prefs: Preferences,
|
2021-01-06 15:04:49 +13:00
|
|
|
}
|
|
|
|
|
2021-02-10 06:38:52 +13:00
|
|
|
#[derive(serde::Deserialize, Default)]
|
2021-01-08 05:38:05 +13:00
|
|
|
pub struct SettingsForm {
|
2021-01-11 15:15:34 +13:00
|
|
|
theme: Option<String>,
|
2021-01-09 17:55:40 +13:00
|
|
|
front_page: Option<String>,
|
2021-01-06 15:04:49 +13:00
|
|
|
layout: Option<String>,
|
2021-01-11 10:08:36 +13:00
|
|
|
wide: Option<String>,
|
2021-01-08 05:38:05 +13:00
|
|
|
comment_sort: Option<String>,
|
2021-01-31 18:43:46 +13:00
|
|
|
show_nsfw: Option<String>,
|
2021-01-06 15:04:49 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
// FUNCTIONS
|
|
|
|
|
|
|
|
// Retrieve cookies from request "Cookie" header
|
2021-02-10 06:38:52 +13:00
|
|
|
pub async fn get(req: Request<()>) -> tide::Result {
|
|
|
|
template(SettingsTemplate { prefs: prefs(req) })
|
2021-01-06 15:04:49 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
// Set cookies using response "Set-Cookie" header
|
2021-02-10 06:38:52 +13:00
|
|
|
pub async fn set(mut req: Request<()>) -> tide::Result {
|
|
|
|
let form: SettingsForm = req.body_form().await.unwrap_or_default();
|
|
|
|
|
|
|
|
let mut res = Response::builder(302)
|
|
|
|
.content_type("text/html")
|
|
|
|
.header("Location", "/settings")
|
|
|
|
.body(r#"Redirecting to <a href="/settings">settings</a>..."#)
|
|
|
|
.build();
|
2021-01-06 15:04:49 +13:00
|
|
|
|
2021-01-31 18:43:46 +13:00
|
|
|
let names = vec!["theme", "front_page", "layout", "wide", "comment_sort", "show_nsfw"];
|
2021-02-10 06:38:52 +13:00
|
|
|
let values = vec![form.theme, form.front_page, form.layout, form.wide, form.comment_sort, form.show_nsfw];
|
2021-01-06 15:04:49 +13:00
|
|
|
|
2021-01-09 14:35:04 +13:00
|
|
|
for (i, name) in names.iter().enumerate() {
|
2021-02-10 06:38:52 +13:00
|
|
|
match values.get(i) {
|
|
|
|
Some(value) => res.insert_cookie(
|
|
|
|
Cookie::build(name.to_owned(), value.to_owned().unwrap_or_default())
|
2021-01-09 14:35:04 +13:00
|
|
|
.path("/")
|
|
|
|
.http_only(true)
|
|
|
|
.expires(OffsetDateTime::now_utc() + Duration::weeks(52))
|
|
|
|
.finish(),
|
|
|
|
),
|
2021-02-10 06:38:52 +13:00
|
|
|
None => res.remove_cookie(Cookie::named(name.to_owned())),
|
2021-01-09 14:35:04 +13:00
|
|
|
};
|
|
|
|
}
|
2021-01-08 05:38:05 +13:00
|
|
|
|
2021-02-10 06:38:52 +13:00
|
|
|
Ok(res)
|
2021-01-06 15:04:49 +13:00
|
|
|
}
|