redsunlib/src/subreddit.rs

108 lines
3.4 KiB
Rust
Raw Normal View History

2020-10-26 09:25:59 +13:00
// CRATES
2020-12-08 08:36:05 +13:00
use crate::utils::{fetch_posts, format_num, format_url, request, val, ErrorTemplate, Params, Post, Subreddit};
2020-12-15 13:35:04 +13:00
use actix_web::{http::StatusCode, web, HttpResponse, Result};
2020-10-26 09:25:59 +13:00
use askama::Template;
2020-12-08 07:53:22 +13:00
use std::convert::TryInto;
2020-11-18 08:37:40 +13:00
2020-10-26 09:25:59 +13:00
// STRUCTS
#[derive(Template)]
#[template(path = "subreddit.html", escape = "none")]
struct SubredditTemplate {
sub: Subreddit,
posts: Vec<Post>,
2020-12-30 14:11:47 +13:00
sort: (String, String),
2020-11-30 15:50:29 +13:00
ends: (String, String),
2020-10-26 09:25:59 +13:00
}
2020-11-20 10:49:32 +13:00
// SERVICES
#[allow(dead_code)]
2020-12-15 13:35:04 +13:00
pub async fn page(web::Path(sub): web::Path<String>, params: web::Query<Params>) -> Result<HttpResponse> {
2020-12-30 14:11:47 +13:00
render(sub, params.sort.clone(), params.t.clone(), (params.before.clone(), params.after.clone())).await
2020-11-20 10:49:32 +13:00
}
2020-12-30 14:11:47 +13:00
pub async fn render(sub_name: String, sort: Option<String>, t: Option<String>, ends: (Option<String>, Option<String>)) -> Result<HttpResponse> {
2020-11-20 10:49:32 +13: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-12-30 14:11:47 +13:00
let timeframe = match &t { Some(val) => format!("&t={}", val), None => String::new() };
2020-11-20 10:49:32 +13:00
// Build the Reddit JSON API url
let url = match ends.0 {
2020-12-30 14:11:47 +13:00
Some(val) => format!("r/{}/{}.json?before={}&count=25{}", sub_name, sorting, val, timeframe),
2020-11-20 10:49:32 +13:00
None => match ends.1 {
2020-12-30 14:11:47 +13:00
Some(val) => format!("r/{}/{}.json?after={}&count=25{}", sub_name, sorting, val, timeframe),
None => format!("r/{}/{}.json?{}", sub_name, sorting, timeframe),
2020-11-20 10:49:32 +13:00
},
};
2020-12-22 05:38:24 +13:00
let sub_result = if !&sub_name.contains("+") {
subreddit(&sub_name).await
} else {
2020-12-29 15:42:46 +13:00
Ok(Subreddit::default())
2020-12-21 14:45:26 +13:00
};
2020-11-21 19:05:27 +13:00
let items_result = fetch_posts(url, String::new()).await;
2020-10-26 09:25:59 +13:00
2020-11-20 17:42:18 +13:00
if sub_result.is_err() || items_result.is_err() {
let s = ErrorTemplate {
message: sub_result.err().unwrap().to_string(),
}
.render()
.unwrap();
2020-11-26 10:53:30 +13:00
Ok(HttpResponse::Ok().status(StatusCode::NOT_FOUND).content_type("text/html").body(s))
2020-10-26 16:57:19 +13:00
} else {
2020-12-24 17:36:49 +13:00
let sub = sub_result.unwrap();
2020-11-20 17:42:18 +13:00
let items = items_result.unwrap();
let s = SubredditTemplate {
sub: sub,
posts: items.0,
2020-12-30 14:11:47 +13:00
sort: (sorting, t.unwrap_or(String::new())),
2020-11-30 15:50:29 +13:00
ends: (before, items.1),
2020-11-20 17:42:18 +13:00
}
.render()
.unwrap();
Ok(HttpResponse::Ok().content_type("text/html").body(s))
2020-11-18 13:03:28 +13:00
}
2020-10-26 09:25:59 +13:00
}
// SUBREDDIT
2020-11-20 17:42:18 +13:00
async fn subreddit(sub: &String) -> Result<Subreddit, &'static str> {
2020-11-19 15:50:59 +13:00
// Build the Reddit JSON API url
2020-12-29 15:42:46 +13:00
let url: String = format!("r/{}/about.json?raw_json=1", sub);
2020-10-26 09:25:59 +13:00
2020-11-19 15:50:59 +13:00
// Send a request to the url, receive JSON in response
2020-11-20 17:42:18 +13:00
let req = request(url).await;
// If the Reddit API returns an error, exit this function
if req.is_err() {
return Err(req.err().unwrap());
}
// Otherwise, grab the JSON output from the request
let res = req.unwrap();
2020-10-26 09:25:59 +13:00
2020-12-26 15:06:33 +13:00
// Metadata regarding the subreddit
2020-11-23 13:43:23 +13:00
let members = res["data"]["subscribers"].as_u64().unwrap_or(0);
2020-11-30 15:50:29 +13:00
let active = res["data"]["accounts_active"].as_u64().unwrap_or(0);
2020-10-26 09:25:59 +13:00
2020-12-26 15:06:33 +13:00
// Fetch subreddit icon either from the community_icon or icon_img value
2020-12-24 17:36:49 +13:00
let community_icon: &str = res["data"]["community_icon"].as_str().unwrap().split("?").collect::<Vec<&str>>()[0];
let icon = if community_icon.is_empty() {
val(&res, "icon_img").await
} else {
community_icon.to_string()
};
2020-11-19 15:50:59 +13:00
let sub = Subreddit {
name: val(&res, "display_name").await,
title: val(&res, "title").await,
description: val(&res, "public_description").await,
2020-12-29 15:42:46 +13:00
info: val(&res, "description_html").await.replace("\\", ""),
2020-12-24 17:36:49 +13:00
icon: format_url(icon).await,
2020-12-08 07:53:22 +13:00
members: format_num(members.try_into().unwrap()),
active: format_num(active.try_into().unwrap()),
2020-11-19 15:50:59 +13:00
};
Ok(sub)
2020-11-30 15:50:29 +13:00
}