Settings with Layouts

This commit is contained in:
spikecodes 2021-01-05 18:04:49 -08:00
parent 2b0193f5ea
commit aa7b4b2af7
16 changed files with 255 additions and 140 deletions

67
Cargo.lock generated
View File

@ -75,7 +75,7 @@ dependencies = [
"log", "log",
"mime", "mime",
"percent-encoding", "percent-encoding",
"pin-project 1.0.2", "pin-project 1.0.3",
"rand", "rand",
"regex", "regex",
"serde", "serde",
@ -93,7 +93,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ca8ce00b267af8ccebbd647de0d61e0674b6e61185cc7a592ff88772bed655" checksum = "b4ca8ce00b267af8ccebbd647de0d61e0674b6e61185cc7a592ff88772bed655"
dependencies = [ dependencies = [
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -247,7 +247,7 @@ dependencies = [
"fxhash", "fxhash",
"log", "log",
"mime", "mime",
"pin-project 1.0.2", "pin-project 1.0.3",
"regex", "regex",
"rustls", "rustls",
"serde", "serde",
@ -267,7 +267,7 @@ checksum = "ad26f77093333e0e7c6ffe54ebe3582d908a104e448723eec6d43d08b07143fb"
dependencies = [ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -346,7 +346,7 @@ checksum = "e5444eec77a9ec2bfe4524139e09195862e981400c4358d3b760cae634e4c4ee"
dependencies = [ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -357,7 +357,7 @@ checksum = "8d3a45e77e34375a7923b1e8febb049bb011f064714a8e17a1a616fef01da13d"
dependencies = [ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -518,9 +518,9 @@ dependencies = [
[[package]] [[package]]
name = "const_fn" name = "const_fn"
version = "0.4.4" version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd51eab21ab4fd6a3bf889e2d0958c0a6e3a61ad04260325e919e652a2a62826" checksum = "28b9d6de7f49e22cf97ad17fc4036ece69300032f45f78f30b4a4482cdc3f4a6"
[[package]] [[package]]
name = "cookie" name = "cookie"
@ -562,7 +562,7 @@ checksum = "41cb0e6161ad61ed084a36ba71fbba9e3ac5aee3606fb607fe08da6acbcf3d8c"
dependencies = [ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -604,7 +604,7 @@ dependencies = [
"heck", "heck",
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -696,7 +696,7 @@ dependencies = [
"proc-macro-hack", "proc-macro-hack",
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -727,7 +727,7 @@ dependencies = [
"futures-sink", "futures-sink",
"futures-task", "futures-task",
"memchr", "memchr",
"pin-project 1.0.2", "pin-project 1.0.3",
"pin-utils", "pin-utils",
"proc-macro-hack", "proc-macro-hack",
"proc-macro-nested", "proc-macro-nested",
@ -880,7 +880,7 @@ dependencies = [
"httparse", "httparse",
"httpdate", "httpdate",
"itoa", "itoa",
"pin-project 1.0.2", "pin-project 1.0.3",
"socket2", "socket2",
"tokio", "tokio",
"tower-service", "tower-service",
@ -1017,6 +1017,7 @@ dependencies = [
"reqwest", "reqwest",
"serde", "serde",
"serde_json", "serde_json",
"time 0.2.23",
"url", "url",
] ]
@ -1249,11 +1250,11 @@ dependencies = [
[[package]] [[package]]
name = "pin-project" name = "pin-project"
version = "1.0.2" version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ccc2237c2c489783abd8c4c80e5450fc0e98644555b1364da68cc29aa151ca7" checksum = "5a83804639aad6ba65345661744708855f9fbcb71176ea8d28d05aeb11d975e7"
dependencies = [ dependencies = [
"pin-project-internal 1.0.2", "pin-project-internal 1.0.3",
] ]
[[package]] [[package]]
@ -1264,18 +1265,18 @@ checksum = "65ad2ae56b6abe3a1ee25f15ee605bacadb9a764edaba9c2bf4103800d4a1895"
dependencies = [ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
name = "pin-project-internal" name = "pin-project-internal"
version = "1.0.2" version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8e8d2bf0b23038a4424865103a4df472855692821aab4e4f5c3312d461d9e5f" checksum = "b7bcc46b8f73443d15bc1c5fecbb315718491fa9187fa483f0e359323cde8b3a"
dependencies = [ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -1286,9 +1287,9 @@ checksum = "c917123afa01924fc84bb20c4c03f004d9c38e5127e3c039bbf7f4b9c76a2f6b"
[[package]] [[package]]
name = "pin-project-lite" name = "pin-project-lite"
version = "0.2.0" version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b063f57ec186e6140e2b8b6921e5f1bd89c7356dda5b33acc5401203ca6131c" checksum = "e36743d754ccdf9954c2e352ce2d4b106e024c814f6499c2dadff80da9a442d8"
[[package]] [[package]]
name = "pin-utils" name = "pin-utils"
@ -1443,7 +1444,7 @@ dependencies = [
"mime", "mime",
"mime_guess", "mime_guess",
"percent-encoding", "percent-encoding",
"pin-project-lite 0.2.0", "pin-project-lite 0.2.1",
"rustls", "rustls",
"serde", "serde",
"serde_urlencoded", "serde_urlencoded",
@ -1564,7 +1565,7 @@ checksum = "c84d3526699cd55261af4b941e4e725444df67aa4f9e6a3564f18030d12672df"
dependencies = [ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -1680,7 +1681,7 @@ dependencies = [
"quote 1.0.8", "quote 1.0.8",
"serde", "serde",
"serde_derive", "serde_derive",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -1696,7 +1697,7 @@ dependencies = [
"serde_derive", "serde_derive",
"serde_json", "serde_json",
"sha1", "sha1",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -1718,9 +1719,9 @@ dependencies = [
[[package]] [[package]]
name = "syn" name = "syn"
version = "1.0.57" version = "1.0.58"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4211ce9909eb971f111059df92c45640aad50a619cf55cd76476be803c4c68e6" checksum = "cc60a3d73ea6594cd712d830cc1f0390fd71542d8c8cd24e70cc54cdfd5e05d5"
dependencies = [ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
@ -1744,7 +1745,7 @@ checksum = "9be73a2caec27583d0046ef3796c3794f868a5bc813db689eed00c7631275cd1"
dependencies = [ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -1811,7 +1812,7 @@ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"standback", "standback",
"syn 1.0.57", "syn 1.0.58",
] ]
[[package]] [[package]]
@ -1899,7 +1900,7 @@ checksum = "9f47026cdc4080c07e49b37087de021820269d996f581aac150ef9e5583eefe3"
dependencies = [ dependencies = [
"cfg-if 1.0.0", "cfg-if 1.0.0",
"log", "log",
"pin-project-lite 0.2.0", "pin-project-lite 0.2.1",
"tracing-core", "tracing-core",
] ]
@ -2094,7 +2095,7 @@ dependencies = [
"log", "log",
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
@ -2128,7 +2129,7 @@ checksum = "b5a48c72f299d80557c7c62e37e7225369ecc0c963964059509fbafe917c7549"
dependencies = [ dependencies = [
"proc-macro2 1.0.24", "proc-macro2 1.0.24",
"quote 1.0.8", "quote 1.0.8",
"syn 1.0.57", "syn 1.0.58",
"wasm-bindgen-backend", "wasm-bindgen-backend",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]

View File

@ -18,3 +18,4 @@ chrono = "0.4.19"
async-recursion = "0.3.1" async-recursion = "0.3.1"
url = "2.2.0" url = "2.2.0"
regex = "1" regex = "1"
time = "0.2.23"

View File

@ -5,7 +5,7 @@ use actix_web::{get, middleware::NormalizePath, web, App, HttpResponse, HttpServ
mod post; mod post;
mod proxy; mod proxy;
mod search; mod search;
// mod settings; mod settings;
mod subreddit; mod subreddit;
mod user; mod user;
mod utils; mod utils;
@ -52,8 +52,8 @@ async fn main() -> std::io::Result<()> {
.route("/favicon.ico/", web::get().to(HttpResponse::Ok)) .route("/favicon.ico/", web::get().to(HttpResponse::Ok))
.route("/robots.txt/", web::get().to(robots)) .route("/robots.txt/", web::get().to(robots))
// SETTINGS SERVICE // SETTINGS SERVICE
// .route("/settings/", web::get().to(settings::get)) .route("/settings/", web::get().to(settings::get))
// .route("/settings/save/", web::post().to(settings::set)) .route("/settings/", web::post().to(settings::set))
// PROXY SERVICE // PROXY SERVICE
.route("/proxy/{url:.*}/", web::get().to(proxy::handler)) .route("/proxy/{url:.*}/", web::get().to(proxy::handler))
// SEARCH SERVICES // SEARCH SERVICES

View File

@ -1,5 +1,5 @@
// CRATES // CRATES
use crate::utils::{error, format_num, format_url, param, request, rewrite_url, val, Comment, Flags, Flair, Post}; use crate::utils::{Comment, Flags, Flair, Post, cookie, error, format_num, format_url, media, param, request, rewrite_url, val};
use actix_web::{HttpRequest, HttpResponse, Result}; use actix_web::{HttpRequest, HttpResponse, Result};
use async_recursion::async_recursion; use async_recursion::async_recursion;
@ -14,6 +14,7 @@ struct PostTemplate {
comments: Vec<Comment>, comments: Vec<Comment>,
post: Post, post: Post,
sort: String, sort: String,
layout: String,
} }
pub async fn item(req: HttpRequest) -> HttpResponse { pub async fn item(req: HttpRequest) -> HttpResponse {
@ -33,7 +34,14 @@ pub async fn item(req: HttpRequest) -> HttpResponse {
let comments = parse_comments(&res[1]).await.unwrap(); let comments = parse_comments(&res[1]).await.unwrap();
// Use the Post and Comment structs to generate a website to show users // Use the Post and Comment structs to generate a website to show users
let s = PostTemplate { comments, post, sort }.render().unwrap(); let s = PostTemplate {
comments,
post,
sort,
layout: cookie(req, "layout"),
}
.render()
.unwrap();
HttpResponse::Ok().content_type("text/html").body(s) HttpResponse::Ok().content_type("text/html").body(s)
} }
// If the Reddit API returns an error, exit and send error page to user // If the Reddit API returns an error, exit and send error page to user
@ -41,26 +49,6 @@ pub async fn item(req: HttpRequest) -> HttpResponse {
} }
} }
// UTILITIES
async fn media(data: &serde_json::Value) -> (String, String) {
let post_type: &str;
let url = if !data["preview"]["reddit_video_preview"]["fallback_url"].is_null() {
post_type = "video";
format_url(data["preview"]["reddit_video_preview"]["fallback_url"].as_str().unwrap_or_default().to_string())
} else if !data["secure_media"]["reddit_video"]["fallback_url"].is_null() {
post_type = "video";
format_url(data["secure_media"]["reddit_video"]["fallback_url"].as_str().unwrap_or_default().to_string())
} else if data["post_hint"].as_str().unwrap_or("") == "image" {
post_type = "image";
format_url(data["preview"]["images"][0]["source"]["url"].as_str().unwrap_or_default().to_string())
} else {
post_type = "link";
data["url"].as_str().unwrap_or_default().to_string()
};
(post_type.to_string(), url)
}
// POSTS // POSTS
async fn parse_post(json: &serde_json::Value) -> Result<Post, &'static str> { async fn parse_post(json: &serde_json::Value) -> Result<Post, &'static str> {
// Retrieve post (as opposed to comments) from JSON // Retrieve post (as opposed to comments) from JSON
@ -91,6 +79,7 @@ async fn parse_post(json: &serde_json::Value) -> Result<Post, &'static str> {
score: format_num(score), score: format_num(score),
upvote_ratio: ratio as i64, upvote_ratio: ratio as i64,
post_type: media.0, post_type: media.0,
thumbnail: format_url(val(post, "thumbnail")),
flair: Flair( flair: Flair(
val(post, "link_flair_text"), val(post, "link_flair_text"),
val(post, "link_flair_background_color"), val(post, "link_flair_background_color"),

View File

@ -1,5 +1,5 @@
// CRATES // CRATES
use crate::utils::{error, fetch_posts, param, Post}; use crate::utils::{cookie, error, fetch_posts, param, Post};
use actix_web::{HttpRequest, HttpResponse}; use actix_web::{HttpRequest, HttpResponse};
use askama::Template; use askama::Template;
@ -19,6 +19,7 @@ struct SearchTemplate {
posts: Vec<Post>, posts: Vec<Post>,
sub: String, sub: String,
params: SearchParams, params: SearchParams,
layout: String,
} }
// SERVICES // SERVICES
@ -44,6 +45,7 @@ pub async fn find(req: HttpRequest) -> HttpResponse {
after: posts.1, after: posts.1,
restrict_sr: param(&path, "restrict_sr"), restrict_sr: param(&path, "restrict_sr"),
}, },
layout: cookie(req, "layout"),
} }
.render() .render()
.unwrap(), .unwrap(),

View File

@ -1,48 +1,48 @@
// // CRATES // CRATES
// use crate::utils::cookies; use crate::utils::cookie;
// use actix_web::{cookie::Cookie, web::Form, HttpRequest, HttpResponse, Result}; // http::Method, use actix_web::{cookie::Cookie, web::Form, HttpRequest, HttpResponse}; // http::Method,
// use askama::Template; use askama::Template;
use time::{Duration, OffsetDateTime};
// // STRUCTS // STRUCTS
// #[derive(Template)] #[derive(Template)]
// #[template(path = "settings.html", escape = "none")] #[template(path = "settings.html", escape = "none")]
// struct SettingsTemplate { struct SettingsTemplate {
// pref_nsfw: String, layout: String,
// } }
// #[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
// pub struct Preferences { pub struct Preferences {
// pref_nsfw: Option<String>, layout: Option<String>,
// } }
// // FUNCTIONS // FUNCTIONS
// // Retrieve cookies from request "Cookie" header // Retrieve cookies from request "Cookie" header
// pub async fn get(req: HttpRequest) -> Result<HttpResponse> { pub async fn get(req: HttpRequest) -> HttpResponse {
// let cookies = cookies(req); let s = SettingsTemplate { layout: cookie(req, "layout") }.render().unwrap();
// let pref_nsfw: String = cookies.get("pref_nsfw").unwrap_or(&String::new()).to_owned(); HttpResponse::Ok().content_type("text/html").body(s)
}
// let s = SettingsTemplate { pref_nsfw }.render().unwrap(); // Set cookies using response "Set-Cookie" header
// Ok(HttpResponse::Ok().content_type("text/html").body(s)) pub async fn set(req: HttpRequest, form: Form<Preferences>) -> HttpResponse {
// } let mut response = HttpResponse::Found();
// // Set cookies using response "Set-Cookie" header match &form.layout {
// pub async fn set(form: Form<Preferences>) -> HttpResponse { Some(value) => response.cookie(
// let nsfw: Cookie = match &form.pref_nsfw { Cookie::build("layout", value)
// Some(value) => Cookie::build("pref_nsfw", value).path("/").secure(true).http_only(true).finish(), .path("/")
// None => Cookie::build("pref_nsfw", "").finish(), .secure(true)
// }; .http_only(true)
.expires(OffsetDateTime::now_utc() + Duration::weeks(52))
.finish(),
),
None => response.del_cookie(&actix_web::HttpMessage::cookie(&req, "layout").unwrap()),
};
// let body = SettingsTemplate { response
// pref_nsfw: form.pref_nsfw.clone().unwrap_or_default(), .content_type("text/html")
// } .set_header("Location", "/settings")
// .render() .body(r#"Redirecting to <a href="/settings">settings</a>..."#)
// .unwrap(); }
// HttpResponse::Found()
// .content_type("text/html")
// .set_header("Set-Cookie", nsfw.to_string())
// .set_header("Location", "/settings")
// .body(body)
// }

View File

@ -1,5 +1,5 @@
// CRATES // CRATES
use crate::utils::{error, fetch_posts, format_num, format_url, param, request, rewrite_url, val, Post, Subreddit}; use crate::utils::{cookie, error, fetch_posts, format_num, format_url, param, request, rewrite_url, val, Post, Subreddit};
use actix_web::{HttpRequest, HttpResponse, Result}; use actix_web::{HttpRequest, HttpResponse, Result};
use askama::Template; use askama::Template;
@ -11,6 +11,7 @@ struct SubredditTemplate {
posts: Vec<Post>, posts: Vec<Post>,
sort: (String, String), sort: (String, String),
ends: (String, String), ends: (String, String),
layout: String,
} }
#[derive(Template)] #[derive(Template)]
@ -19,6 +20,7 @@ struct WikiTemplate {
sub: String, sub: String,
wiki: String, wiki: String,
page: String, page: String,
layout: String,
} }
// SERVICES // SERVICES
@ -40,6 +42,7 @@ pub async fn page(req: HttpRequest) -> HttpResponse {
posts: items.0, posts: items.0,
sort: (sort, param(&path, "t")), sort: (sort, param(&path, "t")),
ends: (param(&path, "after"), items.1), ends: (param(&path, "after"), items.1),
layout: cookie(req, "layout"),
} }
.render() .render()
.unwrap(); .unwrap();
@ -60,6 +63,7 @@ pub async fn wiki(req: HttpRequest) -> HttpResponse {
sub: sub.to_string(), sub: sub.to_string(),
wiki: rewrite_url(res["data"]["content_html"].as_str().unwrap_or_default()), wiki: rewrite_url(res["data"]["content_html"].as_str().unwrap_or_default()),
page: page.to_string(), page: page.to_string(),
layout: String::new(),
} }
.render() .render()
.unwrap(); .unwrap();

View File

@ -1,5 +1,5 @@
// CRATES // CRATES
use crate::utils::{error, fetch_posts, format_url, nested_val, param, request, Post, User}; use crate::utils::{cookie, error, fetch_posts, format_url, nested_val, param, request, Post, User};
use actix_web::{HttpRequest, HttpResponse, Result}; use actix_web::{HttpRequest, HttpResponse, Result};
use askama::Template; use askama::Template;
use chrono::{TimeZone, Utc}; use chrono::{TimeZone, Utc};
@ -12,6 +12,7 @@ struct UserTemplate {
posts: Vec<Post>, posts: Vec<Post>,
sort: (String, String), sort: (String, String),
ends: (String, String), ends: (String, String),
layout: String,
} }
// FUNCTIONS // FUNCTIONS
@ -34,6 +35,7 @@ pub async fn profile(req: HttpRequest) -> HttpResponse {
posts: items.0, posts: items.0,
sort: (sort, param(&path, "t")), sort: (sort, param(&path, "t")),
ends: (param(&path, "after"), items.1), ends: (param(&path, "after"), items.1),
layout: cookie(req, "layout"),
} }
.render() .render()
.unwrap(); .unwrap();

View File

@ -1,9 +1,11 @@
// use std::collections::HashMap; // use std::collections::HashMap;
use std::collections::HashMap;
// //
// CRATES // CRATES
// //
use actix_web::{HttpResponse, Result}; use actix_web::{cookie::Cookie, HttpResponse, Result};
use askama::Template; use askama::Template;
use base64::encode; use base64::encode;
use chrono::{TimeZone, Utc}; use chrono::{TimeZone, Utc};
@ -37,6 +39,7 @@ pub struct Post {
pub post_type: String, pub post_type: String,
pub flair: Flair, pub flair: Flair,
pub flags: Flags, pub flags: Flags,
pub thumbnail: String,
pub media: String, pub media: String,
pub time: String, pub time: String,
} }
@ -91,6 +94,7 @@ pub struct Params {
#[template(path = "error.html", escape = "none")] #[template(path = "error.html", escape = "none")]
pub struct ErrorTemplate { pub struct ErrorTemplate {
pub message: String, pub message: String,
pub layout: String,
} }
// //
@ -100,27 +104,14 @@ pub struct ErrorTemplate {
// Grab a query param from a url // Grab a query param from a url
pub fn param(path: &str, value: &str) -> String { pub fn param(path: &str, value: &str) -> String {
let url = Url::parse(format!("https://libredd.it/{}", path).as_str()).unwrap(); let url = Url::parse(format!("https://libredd.it/{}", path).as_str()).unwrap();
let pairs: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect(); let pairs: HashMap<_, _> = url.query_pairs().into_owned().collect();
pairs.get(value).unwrap_or(&String::new()).to_owned() pairs.get(value).unwrap_or(&String::new()).to_owned()
} }
// Cookies from request // Cookie value from request
// pub fn cookies(req: HttpRequest) -> HashMap<String, String> { pub fn cookie(req: actix_web::HttpRequest, name: &str) -> String {
// let mut result: HashMap<String, String> = HashMap::new(); actix_web::HttpMessage::cookie(&req, name).unwrap_or_else(|| Cookie::new(name, "")).value().to_string()
}
// let cookies: Vec<Cookie> = req
// .headers()
// .get_all("Cookie")
// .map(|value| value.to_str().unwrap())
// .map(|unparsed| Cookie::parse(unparsed).unwrap())
// .collect();
// for cookie in cookies {
// result.insert(cookie.name().to_string(), cookie.value().to_string());
// }
// result
// }
// Direct urls to proxy if proxy is enabled // Direct urls to proxy if proxy is enabled
pub fn format_url(url: String) -> String { pub fn format_url(url: String) -> String {
@ -148,6 +139,25 @@ pub fn format_num(num: i64) -> String {
} }
} }
pub async fn media(data: &serde_json::Value) -> (String, String) {
let post_type: &str;
let url = if !data["preview"]["reddit_video_preview"]["fallback_url"].is_null() {
post_type = "video";
format_url(data["preview"]["reddit_video_preview"]["fallback_url"].as_str().unwrap_or_default().to_string())
} else if !data["secure_media"]["reddit_video"]["fallback_url"].is_null() {
post_type = "video";
format_url(data["secure_media"]["reddit_video"]["fallback_url"].as_str().unwrap_or_default().to_string())
} else if data["post_hint"].as_str().unwrap_or("") == "image" {
post_type = "image";
format_url(data["preview"]["images"][0]["source"]["url"].as_str().unwrap_or_default().to_string())
} else {
post_type = "link";
data["url"].as_str().unwrap_or_default().to_string()
};
(post_type.to_string(), url)
}
// //
// JSON PARSING // JSON PARSING
// //
@ -187,12 +197,16 @@ pub async fn fetch_posts(path: &str, fallback_title: String) -> Result<(Vec<Post
// For each post from posts list // For each post from posts list
for post in post_list { for post in post_list {
let img = format_url(val(post, "thumbnail"));
let unix_time: i64 = post["data"]["created_utc"].as_f64().unwrap_or_default().round() as i64; let unix_time: i64 = post["data"]["created_utc"].as_f64().unwrap_or_default().round() as i64;
let score = post["data"]["score"].as_i64().unwrap_or_default(); let score = post["data"]["score"].as_i64().unwrap_or_default();
let ratio: f64 = post["data"]["upvote_ratio"].as_f64().unwrap_or(1.0) * 100.0; let ratio: f64 = post["data"]["upvote_ratio"].as_f64().unwrap_or(1.0) * 100.0;
let title = val(post, "title"); let title = val(post, "title");
// Determine the type of media along with the media URL
let media = media(&post["data"]).await;
dbg!(post["data"]["id"].to_string());
posts.push(Post { posts.push(Post {
id: val(post, "id"), id: val(post, "id"),
title: if title.is_empty() { fallback_title.to_owned() } else { title }, title: if title.is_empty() { fallback_title.to_owned() } else { title },
@ -206,8 +220,9 @@ pub async fn fetch_posts(path: &str, fallback_title: String) -> Result<(Vec<Post
), ),
score: format_num(score), score: format_num(score),
upvote_ratio: ratio as i64, upvote_ratio: ratio as i64,
post_type: "link".to_string(), post_type: media.0,
media: img, thumbnail: format_url(val(post, "thumbnail")),
media: media.1,
flair: Flair( flair: Flair(
val(post, "link_flair_text"), val(post, "link_flair_text"),
val(post, "link_flair_background_color"), val(post, "link_flair_background_color"),
@ -234,7 +249,12 @@ pub async fn fetch_posts(path: &str, fallback_title: String) -> Result<(Vec<Post
// //
pub async fn error(msg: String) -> HttpResponse { pub async fn error(msg: String) -> HttpResponse {
let body = ErrorTemplate { message: msg }.render().unwrap_or_default(); let body = ErrorTemplate {
message: msg,
layout: String::new(),
}
.render()
.unwrap_or_default();
HttpResponse::NotFound().content_type("text/html").body(body) HttpResponse::NotFound().content_type("text/html").body(body)
} }

View File

@ -37,7 +37,8 @@ nav {
min-height: 40px; min-height: 40px;
} }
nav #lib, nav #github, nav #version { color: white; } nav * { color: white; }
nav #reddit { color: var(--accent); }
nav #version { opacity: 25%; } nav #version { opacity: 25%; }
main { main {
@ -93,7 +94,7 @@ aside {
max-width: 350px; max-width: 350px;
} }
.panel { .post, .panel {
border: 1px solid var(--highlighted); border: 1px solid var(--highlighted);
} }
@ -408,7 +409,6 @@ input[type="submit"]:hover { color: var(--accent); }
.post_thumbnail { .post_thumbnail {
object-fit: cover; object-fit: cover;
width: auto; width: auto;
flex-shrink: 0;
border-radius: 5px; border-radius: 5px;
border: 1px solid var(--foreground); border: 1px solid var(--foreground);
max-width: 20%; max-width: 20%;
@ -554,6 +554,81 @@ input[type="submit"]:hover { color: var(--accent); }
background: black; background: black;
} }
/* Layouts */
#compact .post:not(.highlighted) {
border-radius: 0;
margin: 0;
padding: 0;
}
#compact .post:not(:last-of-type):not(.highlighted):not(.stickied) {
border-bottom: 0;
}
#compact .post_left {
border-radius: 0;
}
#compact .post_header {
font-size: 14px;
}
#compact .post_title {
margin-top: 5px;
}
#compact .post_text {
padding: 10px;
}
#compact .post_thumbnail {
max-width: 75px;
max-height: 75px;
}
#compact #footer {
margin-top: 10px;
}
#card .post_right {
flex-direction: column;
}
#card .post:not(.highlighted) .post_media {
margin-top: 0;
margin-bottom: 15px;
}
/* Settings */
#settings {
display: flex;
flex-direction: column;
align-items: center;
}
#prefs {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
background: var(--post);
border-radius: 5px;
}
#prefs > select {
border-radius: 5px;
margin-left: 20px;
}
#save {
background: var(--highlighted);
padding: 10px 15px;
border-radius: 5px;
margin-top: 20px;
}
/* Markdown */ /* Markdown */
.md > *:not(:first-child) { .md > *:not(:first-child) {

View File

@ -11,10 +11,15 @@
<link rel="stylesheet" href="/style.css"> <link rel="stylesheet" href="/style.css">
{% endblock %} {% endblock %}
</head> </head>
<body> <body {% if layout != "" %}id="{{ layout }}"{% endif %}>
<!-- NAVIGATION BAR --> <!-- NAVIGATION BAR -->
<nav> <nav>
<a id="logo" href="/"><span id="lib">lib</span>reddit. <span id="version">v{{ env!("CARGO_PKG_VERSION") }}</span></a> <p id="logo">
<a id="libreddit" href="/">
<span id="lib">lib</span><span id="reddit">reddit.</span>
</a>
<span id="version">v{{ env!("CARGO_PKG_VERSION") }}</span>
</p>
{% block search %}{% endblock %} {% block search %}{% endblock %}
<a id="github" href="https://github.com/spikecodes/libreddit">GITHUB</a> <a id="github" href="https://github.com/spikecodes/libreddit">GITHUB</a>
</nav> </nav>

View File

@ -39,7 +39,7 @@
<div id="column_one"> <div id="column_one">
<!-- POST CONTENT --> <!-- POST CONTENT -->
<div class="post highlighted panel"> <div class="post highlighted">
<div class="post_left"> <div class="post_left">
<p class="post_score">{{ post.score }}</p> <p class="post_score">{{ post.score }}</p>
{% if post.flags.nsfw %}<div class="nsfw">NSFW</div>{% endif %} {% if post.flags.nsfw %}<div class="nsfw">NSFW</div>{% endif %}

View File

@ -21,7 +21,7 @@
</form> </form>
{% for post in posts %} {% for post in posts %}
{% if post.title != "Comment" %} {% if post.title != "Comment" %}
<div class="post panel"> <div class="post">
<div class="post_left"> <div class="post_left">
<p class="post_score">{{ post.score }}</p> <p class="post_score">{{ post.score }}</p>
{% if post.flags.nsfw %}<div class="nsfw">NSFW</div>{% endif %} {% if post.flags.nsfw %}<div class="nsfw">NSFW</div>{% endif %}

View File

@ -9,10 +9,14 @@
{% block body %} {% block body %}
<main> <main>
<form action="/settings/save" method="POST"> <form id="settings" action="/settings" method="POST">
<label for="pref_nsfw">NSFW</label> <div id="prefs">
<input type="checkbox" name="pref_nsfw" id="pref_nsfw" {% if pref_nsfw == "on" %}checked{% endif %}> <label for="layout">Layout:</label>
<input id="sort_submit" type="submit" value="&rarr;"> <select name="layout">
{% call utils::options(layout, ["card", "clean", "compact"], "clean") %}
</select>
</div>
<input id="save" type="submit" value="Save">
</form> </form>
</main> </main>
{% endblock %} {% endblock %}

View File

@ -28,7 +28,7 @@
</select>{% endif %} </select>{% endif %}
</form> </form>
{% for post in posts %} {% for post in posts %}
<div class="post {% if post.flags.stickied %}stickied{% endif %} panel"> <div class="post {% if post.flags.stickied %}stickied{% endif %}">
<div class="post_left"> <div class="post_left">
<p class="post_score">{{ post.score }}</p> <p class="post_score">{{ post.score }}</p>
{% if post.flags.nsfw %}<div class="nsfw">NSFW</div>{% endif %} {% if post.flags.nsfw %}<div class="nsfw">NSFW</div>{% endif %}
@ -49,7 +49,13 @@
<a href="{{ post.permalink }}">{{ post.title }}</a> <a href="{{ post.permalink }}">{{ post.title }}</a>
</p> </p>
</div> </div>
<img class="post_thumbnail" src="{{ post.media }}">
<!-- POST MEDIA/THUMBNAIL -->
{% if layout == "card" && post.post_type == "image" %}
<img class="post_media" src="{{ post.media }}"/>
{% else if layout != "card" %}
<img class="post_thumbnail" src="{{ post.thumbnail }}">
{% endif %}
</div> </div>
</div> </div>
{% endfor %} {% endfor %}

View File

@ -18,7 +18,7 @@
</form> </form>
{% for post in posts %} {% for post in posts %}
{% if post.title != "Comment" %} {% if post.title != "Comment" %}
<div class="post panel"> <div class="post">
<div class="post_left"> <div class="post_left">
<p class="post_score">{{ post.score }}</p> <p class="post_score">{{ post.score }}</p>
{% if post.flags.nsfw %}<div class="nsfw">NSFW</div>{% endif %} {% if post.flags.nsfw %}<div class="nsfw">NSFW</div>{% endif %}
@ -42,7 +42,13 @@
<a href="{{ post.permalink }}">{{ post.title }}</a> <a href="{{ post.permalink }}">{{ post.title }}</a>
</p> </p>
</div> </div>
<img class="post_thumbnail" src="{{ post.media }}">
<!-- POST MEDIA/THUMBNAIL -->
{% if layout == "card" && post.post_type == "image" %}
<img class="post_media" src="{{ post.media }}"/>
{% else if layout != "card" %}
<img class="post_thumbnail" src="{{ post.thumbnail }}">
{% endif %}
</div> </div>
</div> </div>
{% else %} {% else %}