libreddit/src/popular.rs

58 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-12-15 01:35:04 +01:00
use actix_web::{http::StatusCode, web, HttpResponse, Result};
2020-11-30 03:50:29 +01:00
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-12-30 02:11:47 +01:00
sort: (String, 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-12-30 02:11:47 +01:00
async fn render(sort: Option<String>, t: Option<String>, ends: (Option<String>, Option<String>)) -> Result<HttpResponse> {
2020-11-19 22:49:32 +01:00
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-12-30 02:11:47 +01:00
let timeframe = match &t { Some(val) => format!("&t={}", val), None => String::new() };
2020-11-19 22:49:32 +01:00
// Build the Reddit JSON API url
let url = match ends.0 {
2020-12-30 02:11:47 +01:00
Some(val) => format!("r/popular/{}.json?before={}&count=25{}", sorting, val, timeframe),
2020-11-19 22:49:32 +01:00
None => match ends.1 {
2020-12-30 02:11:47 +01:00
Some(val) => format!("r/popular/{}.json?after={}&count=25{}", sorting, val, timeframe),
None => format!("r/popular/{}.json?{}", sorting, timeframe),
2020-11-19 22:49:32 +01:00
},
};
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,
2020-12-30 02:11:47 +01:00
sort: (sorting, t.unwrap_or(String::new())),
2020-11-20 05:42:18 +01:00
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
pub async fn page(params: web::Query<Params>) -> Result<HttpResponse> {
2020-12-30 02:11:47 +01:00
render(params.sort.clone(), params.t.clone(), (params.before.clone(), params.after.clone())).await
2020-10-26 04:57:19 +01:00
}