libreddit/src/popular.rs

57 lines
1.7 KiB
Rust
Raw Normal View History

2020-10-25 21:25:59 +01:00
// CRATES
2020-11-25 22:53:30 +01:00
use crate::utils::{fetch_posts, ErrorTemplate, Params, Post};
2020-11-30 03:50:29 +01:00
use actix_web::{get, http::StatusCode, web, HttpResponse, Result};
use askama::Template;
2020-11-18 01:03:28 +01:00
2020-10-25 21:25:59 +01:00
// STRUCTS
#[derive(Template)]
#[template(path = "popular.html", escape = "none")]
struct PopularTemplate {
2020-11-17 20:37:40 +01:00
posts: Vec<Post>,
2020-10-26 04:57:19 +01:00
sort: String,
2020-11-19 22:49:32 +01:00
ends: (String, String),
2020-10-25 21:25:59 +01:00
}
2020-10-26 04:57:19 +01:00
// RENDER
2020-11-19 22:49:32 +01:00
async fn render(sub_name: String, sort: Option<String>, ends: (Option<String>, Option<String>)) -> Result<HttpResponse> {
let sorting = sort.unwrap_or("hot".to_string());
let before = ends.1.clone().unwrap_or(String::new()); // If there is an after, there must be a before
2020-10-26 04:57:19 +01:00
2020-11-19 22:49:32 +01:00
// Build the Reddit JSON API url
let url = match ends.0 {
Some(val) => format!("https://www.reddit.com/r/{}/{}.json?before={}&count=25", sub_name, sorting, val),
None => match ends.1 {
Some(val) => format!("https://www.reddit.com/r/{}/{}.json?after={}&count=25", sub_name, sorting, val),
None => format!("https://www.reddit.com/r/{}/{}.json", sub_name, sorting),
},
};
2020-11-21 07:05:27 +01:00
let items_result = fetch_posts(url, String::new()).await;
2020-11-20 05:42:18 +01:00
if items_result.is_err() {
let s = ErrorTemplate {
message: items_result.err().unwrap().to_string(),
}
.render()
.unwrap();
2020-11-25 22:53:30 +01:00
Ok(HttpResponse::Ok().status(StatusCode::NOT_FOUND).content_type("text/html").body(s))
2020-11-20 05:42:18 +01:00
} else {
let items = items_result.unwrap();
let s = PopularTemplate {
posts: items.0,
sort: sorting,
ends: (before, items.1),
}
.render()
.unwrap();
Ok(HttpResponse::Ok().content_type("text/html").body(s))
2020-11-19 22:49:32 +01:00
}
2020-10-25 21:25:59 +01:00
}
2020-10-26 04:57:19 +01:00
// SERVICES
#[get("/")]
pub async fn page(params: web::Query<Params>) -> Result<HttpResponse> {
2020-11-19 22:49:32 +01:00
render("popular".to_string(), params.sort.clone(), (params.before.clone(), params.after.clone())).await
2020-10-26 04:57:19 +01:00
}