libreddit/src/settings.rs

125 lines
3.2 KiB
Rust
Raw Normal View History

2021-03-17 23:30:33 +01:00
use std::collections::HashMap;
2021-01-06 03:04:49 +01:00
// CRATES
2021-03-17 23:30:33 +01:00
use crate::server::ResponseExt;
2021-02-25 06:29:23 +01:00
use crate::utils::{redirect, template, Preferences};
2021-01-06 03:04:49 +01:00
use askama::Template;
2021-03-17 23:30:33 +01:00
use cookie::Cookie;
use futures_lite::StreamExt;
use hyper::{Body, Request, Response};
2021-01-06 03:04:49 +01:00
use time::{Duration, OffsetDateTime};
// STRUCTS
#[derive(Template)]
2021-01-07 17:38:05 +01:00
#[template(path = "settings.html")]
2021-01-06 03:04:49 +01:00
struct SettingsTemplate {
2021-01-09 02:50:03 +01:00
prefs: Preferences,
2021-01-06 03:04:49 +01:00
}
2021-03-17 23:30:33 +01:00
#[derive(serde::Deserialize, Default, Debug)]
#[serde(default)]
2021-03-09 03:49:06 +01:00
pub struct Form {
2021-01-11 03:15:34 +01:00
theme: Option<String>,
2021-01-09 05:55:40 +01:00
front_page: Option<String>,
2021-01-06 03:04:49 +01:00
layout: Option<String>,
2021-01-10 22:08:36 +01:00
wide: Option<String>,
2021-01-07 17:38:05 +01:00
comment_sort: Option<String>,
2021-01-31 06:43:46 +01:00
show_nsfw: Option<String>,
redirect: Option<String>,
subscriptions: Option<String>,
2021-01-06 03:04:49 +01:00
}
// FUNCTIONS
// Retrieve cookies from request "Cookie" header
2021-03-17 23:30:33 +01:00
pub async fn get(req: Request<Body>) -> Result<Response<Body>, String> {
2021-02-25 06:29:23 +01:00
template(SettingsTemplate { prefs: Preferences::new(req) })
2021-01-06 03:04:49 +01:00
}
// Set cookies using response "Set-Cookie" header
2021-03-17 23:30:33 +01:00
pub async fn set(req: Request<Body>) -> Result<Response<Body>, String> {
// Split the body into parts
let (parts, mut body) = req.into_parts();
// Grab existing cookies
let mut cookies = Vec::new();
for header in parts.headers.get_all("Cookie") {
if let Ok(cookie) = Cookie::parse(header.to_str().unwrap_or_default()) {
cookies.push(cookie);
}
}
// Aggregate the body...
// let whole_body = hyper::body::aggregate(req).await.map_err(|e| e.to_string())?;
let body_bytes = body
.try_fold(Vec::new(), |mut data, chunk| {
data.extend_from_slice(&chunk);
Ok(data)
})
.await
.map_err(|e| e.to_string())?;
let form = url::form_urlencoded::parse(&body_bytes).collect::<HashMap<_, _>>();
2021-02-14 00:02:38 +01:00
let mut res = redirect("/settings".to_string());
2021-01-06 03:04:49 +01:00
2021-03-17 23:30:33 +01:00
let names = vec!["theme", "front_page", "layout", "wide", "comment_sort", "show_nsfw", "subscriptions"];
2021-01-06 03:04:49 +01:00
2021-03-17 23:30:33 +01:00
for name in names {
match form.get(name) {
Some(value) => res.insert_cookie(
2021-03-17 23:30:33 +01:00
Cookie::build(name.to_owned(), value.to_owned())
2021-01-09 02:35:04 +01:00
.path("/")
.http_only(true)
.expires(OffsetDateTime::now_utc() + Duration::weeks(52))
.finish(),
),
2021-03-17 23:30:33 +01:00
None => res.remove_cookie(name.to_string()),
2021-01-09 02:35:04 +01:00
};
}
2021-01-07 17:38:05 +01:00
Ok(res)
2021-01-06 03:04:49 +01:00
}
// Set cookies using response "Set-Cookie" header
2021-03-17 23:30:33 +01:00
pub async fn restore(req: Request<Body>) -> Result<Response<Body>, String> {
// Split the body into parts
let (parts, _) = req.into_parts();
// Grab existing cookies
let mut cookies = Vec::new();
for header in parts.headers.get_all("Cookie") {
if let Ok(cookie) = Cookie::parse(header.to_str().unwrap_or_default()) {
cookies.push(cookie);
}
}
let query = parts.uri.query().unwrap_or_default().as_bytes();
2021-03-17 23:30:33 +01:00
let form = url::form_urlencoded::parse(query).collect::<HashMap<_, _>>();
let names = vec!["theme", "front_page", "layout", "wide", "comment_sort", "show_nsfw", "subscriptions"];
let path = match form.get("redirect") {
Some(value) => format!("/{}/", value),
2021-02-14 00:02:38 +01:00
None => "/".to_string(),
};
2021-02-14 00:02:38 +01:00
let mut res = redirect(path);
2021-03-17 23:30:33 +01:00
for name in names {
match form.get(name) {
Some(value) => res.insert_cookie(
2021-03-17 23:30:33 +01:00
Cookie::build(name.to_owned(), value.to_owned())
.path("/")
.http_only(true)
.expires(OffsetDateTime::now_utc() + Duration::weeks(52))
.finish(),
),
2021-03-17 23:30:33 +01:00
None => res.remove_cookie(name.to_string()),
};
}
Ok(res)
}