redlib/src/popular.rs

56 lines
1.6 KiB
Rust
Raw Normal View History

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