redsunlib/src/post.rs

217 lines
6.8 KiB
Rust
Raw Normal View History

2020-10-26 09:25:59 +13:00
// CRATES
2021-03-18 11:30:33 +13:00
use crate::client::json;
2021-03-12 17:15:26 +13:00
use crate::esc;
2021-03-18 11:30:33 +13:00
use crate::server::RequestExt;
use crate::utils::{cookie, error, format_num, format_url, param, rewrite_urls, template, time, val, Author, Comment, Flags, Flair, FlairPart, Media, Post, Preferences};
use hyper::{Body, Request, Response};
2020-12-15 13:35:04 +13:00
2020-12-20 16:54:46 +13:00
use async_recursion::async_recursion;
2020-10-26 09:25:59 +13:00
use askama::Template;
2020-11-30 15:50:29 +13:00
2020-10-26 09:25:59 +13:00
// STRUCTS
#[derive(Template)]
#[template(path = "post.html", escape = "none")]
struct PostTemplate {
comments: Vec<Comment>,
post: Post,
2020-10-26 16:57:19 +13:00
sort: String,
2021-01-11 10:20:47 +13:00
prefs: Preferences,
single_thread: bool,
2020-10-26 09:25:59 +13:00
}
2021-03-18 11:30:33 +13:00
pub async fn item(req: Request<Body>) -> Result<Response<Body>, String> {
2021-01-08 05:38:05 +13:00
// Build Reddit API path
2021-03-18 11:30:33 +13:00
let mut path: String = format!("{}.json?{}&raw_json=1", req.uri().path(), req.uri().query().unwrap_or_default());
2021-01-08 07:32:55 +13:00
// Set sort to sort query parameter
let mut sort: String = param(&path, "sort");
// Grab default comment sort method from Cookies
2021-01-09 14:50:03 +13:00
let default_sort = cookie(&req, "comment_sort");
2021-01-08 07:32:55 +13:00
// If there's no sort query but there's a default sort, set sort to default_sort
if sort.is_empty() && !default_sort.is_empty() {
sort = default_sort;
2021-03-18 11:30:33 +13:00
path = format!("{}.json?{}&sort={}&raw_json=1", req.uri().path(), req.uri().query().unwrap_or_default(), sort);
2021-01-08 07:32:55 +13:00
}
2021-01-01 12:54:13 +13:00
2020-12-22 18:40:06 +13:00
// Log the post ID being fetched in debug mode
#[cfg(debug_assertions)]
2021-03-18 11:30:33 +13:00
dbg!(req.param("id").unwrap_or_default());
2021-02-14 12:02:38 +13:00
let single_thread = req.param("comment_id").is_some();
let highlighted_comment = &req.param("comment_id").unwrap_or_default();
2021-01-02 19:21:43 +13:00
2020-11-21 18:04:35 +13:00
// Send a request to the url, receive JSON in response
2021-03-18 11:30:33 +13:00
match json(path).await {
2021-01-01 12:54:13 +13:00
// Otherwise, grab the JSON output from the request
2021-01-02 12:28:13 +13:00
Ok(res) => {
// Parse the JSON into Post and Comment structs
2021-01-07 18:27:24 +13:00
let post = parse_post(&res[0]).await;
2021-03-18 11:30:33 +13:00
let comments = parse_comments(&res[1], &post.permalink, &post.author.name, highlighted_comment).await;
2021-01-02 12:28:13 +13:00
// Use the Post and Comment structs to generate a website to show users
template(PostTemplate {
2021-01-11 10:20:47 +13:00
comments,
post,
sort,
2021-02-25 18:29:23 +13:00
prefs: Preferences::new(req),
single_thread,
})
2021-01-02 19:21:43 +13:00
}
2021-01-02 12:28:13 +13:00
// If the Reddit API returns an error, exit and send error page to user
2021-02-21 15:36:30 +13:00
Err(msg) => error(req, msg).await,
2020-10-26 09:25:59 +13:00
}
}
2020-10-26 13:52:57 +13:00
// POSTS
2021-01-07 18:27:24 +13:00
async fn parse_post(json: &serde_json::Value) -> Post {
2020-12-23 15:29:43 +13:00
// Retrieve post (as opposed to comments) from JSON
let post: &serde_json::Value = &json["data"]["children"][0];
2020-10-26 09:25:59 +13:00
2020-12-23 15:29:43 +13:00
// Grab UTC time as unix timestamp
2021-03-10 04:22:17 +13:00
let (rel_time, created) = time(post["data"]["created_utc"].as_f64().unwrap_or_default());
// Parse post score and upvote ratio
2021-01-04 18:31:21 +13:00
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;
2020-10-26 09:25:59 +13:00
2020-12-23 15:29:43 +13:00
// Determine the type of media along with the media URL
2021-02-25 18:29:23 +13:00
let (post_type, media, gallery) = Media::parse(&post["data"]).await;
2020-12-23 15:29:43 +13:00
// Build a post using data parsed from Reddit post API
2021-01-07 18:27:24 +13:00
Post {
id: val(post, "id"),
2021-03-12 17:15:26 +13:00
title: esc!(post, "title"),
community: val(post, "subreddit"),
2021-02-10 18:54:55 +13:00
body: rewrite_urls(&val(post, "selftext_html")).replace("\\", ""),
2021-01-17 12:02:24 +13:00
author: Author {
name: val(post, "author"),
flair: Flair {
2021-02-25 18:29:23 +13:00
flair_parts: FlairPart::parse(
2021-02-15 11:53:09 +13:00
post["data"]["author_flair_type"].as_str().unwrap_or_default(),
2021-01-17 12:02:24 +13:00
post["data"]["author_flair_richtext"].as_array(),
post["data"]["author_flair_text"].as_str(),
),
2021-03-12 17:15:26 +13:00
text: esc!(post, "link_flair_text"),
2021-01-17 12:02:24 +13:00
background_color: val(post, "author_flair_background_color"),
foreground_color: val(post, "author_flair_text_color"),
},
distinguished: val(post, "distinguished"),
2021-01-13 10:43:03 +13:00
},
permalink: val(post, "permalink"),
2020-12-08 07:32:46 +13:00
score: format_num(score),
upvote_ratio: ratio as i64,
2021-01-07 18:27:24 +13:00
post_type,
2021-01-18 09:58:12 +13:00
media,
thumbnail: Media {
url: format_url(val(post, "thumbnail").as_str()),
alt_url: String::new(),
2021-01-18 09:58:12 +13:00
width: post["data"]["thumbnail_width"].as_i64().unwrap_or_default(),
height: post["data"]["thumbnail_height"].as_i64().unwrap_or_default(),
poster: "".to_string(),
2021-01-18 09:58:12 +13:00
},
2021-01-14 09:52:00 +13:00
flair: Flair {
2021-02-25 18:29:23 +13:00
flair_parts: FlairPart::parse(
2021-02-15 11:53:09 +13:00
post["data"]["link_flair_type"].as_str().unwrap_or_default(),
2021-01-14 09:52:00 +13:00
post["data"]["link_flair_richtext"].as_array(),
post["data"]["link_flair_text"].as_str(),
),
2021-03-12 17:15:26 +13:00
text: esc!(post, "link_flair_text"),
2021-01-13 10:43:03 +13:00
background_color: val(post, "link_flair_background_color"),
foreground_color: if val(post, "link_flair_text_color") == "dark" {
2020-11-17 17:36:36 +13:00
"black".to_string()
} else {
"white".to_string()
},
2021-01-13 10:43:03 +13:00
},
2020-12-30 16:01:02 +13:00
flags: Flags {
nsfw: post["data"]["over_18"].as_bool().unwrap_or(false),
stickied: post["data"]["stickied"].as_bool().unwrap_or(false),
2020-12-30 16:01:02 +13:00
},
2021-01-12 11:08:12 +13:00
domain: val(post, "domain"),
rel_time,
2021-01-17 08:50:12 +13:00
created,
comments: format_num(post["data"]["num_comments"].as_i64().unwrap_or_default()),
2021-02-07 09:05:11 +13:00
gallery,
2021-01-07 18:27:24 +13:00
}
2020-10-26 09:25:59 +13:00
}
// COMMENTS
2020-12-20 16:54:46 +13:00
#[async_recursion]
async fn parse_comments(json: &serde_json::Value, post_link: &str, post_author: &str, highlighted_comment: &str) -> Vec<Comment> {
2020-12-20 16:54:46 +13:00
// Separate the comment JSON into a Vector of comments
2021-01-12 15:05:13 +13:00
let comment_data = match json["data"]["children"].as_array() {
Some(f) => f.to_owned(),
2021-01-13 16:52:02 +13:00
None => Vec::new(),
2021-01-12 15:05:13 +13:00
};
2020-10-26 09:25:59 +13:00
let mut comments: Vec<Comment> = Vec::new();
2020-10-26 16:57:19 +13:00
2020-12-20 16:54:46 +13:00
// For each comment, retrieve the values to build a Comment object
2020-12-23 15:29:43 +13:00
for comment in comment_data {
2021-02-15 11:53:09 +13:00
let kind = comment["kind"].as_str().unwrap_or_default().to_string();
let data = &comment["data"];
2021-03-10 04:22:17 +13:00
let unix_time = data["created_utc"].as_f64().unwrap_or_default();
let (rel_time, created) = time(unix_time);
2020-12-20 16:54:46 +13:00
2021-03-10 04:22:17 +13:00
let edited = match data["edited"].as_f64() {
2021-02-15 11:53:09 +13:00
Some(stamp) => time(stamp),
None => (String::new(), String::new()),
};
let score = data["score"].as_i64().unwrap_or(0);
2021-02-10 18:54:55 +13:00
let body = rewrite_urls(&val(&comment, "body_html"));
2020-10-26 13:52:57 +13:00
2021-02-25 06:26:01 +13:00
// If this comment contains replies, handle those too
2021-02-15 11:53:09 +13:00
let replies: Vec<Comment> = if data["replies"].is_object() {
parse_comments(&data["replies"], post_link, post_author, highlighted_comment).await
2020-12-20 16:54:46 +13:00
} else {
Vec::new()
};
2021-02-14 12:02:38 +13:00
let parent_kind_and_id = val(&comment, "parent_id");
2021-02-19 07:04:59 +13:00
let parent_info = parent_kind_and_id.split('_').collect::<Vec<&str>>();
2021-02-14 12:02:38 +13:00
let id = val(&comment, "id");
let highlighted = id == highlighted_comment;
2021-02-14 12:02:38 +13:00
2020-10-26 09:25:59 +13:00
comments.push(Comment {
id,
2021-02-15 11:53:09 +13:00
kind,
parent_id: parent_info[1].to_string(),
parent_kind: parent_info[0].to_string(),
post_link: post_link.to_string(),
post_author: post_author.to_string(),
2021-01-02 09:33:57 +13:00
body,
2021-01-17 12:02:24 +13:00
author: Author {
name: val(&comment, "author"),
flair: Flair {
2021-02-25 18:29:23 +13:00
flair_parts: FlairPart::parse(
2021-02-15 11:53:09 +13:00
data["author_flair_type"].as_str().unwrap_or_default(),
data["author_flair_richtext"].as_array(),
data["author_flair_text"].as_str(),
2021-01-17 12:02:24 +13:00
),
2021-03-12 17:15:26 +13:00
text: esc!(&comment, "link_flair_text"),
2021-01-17 12:02:24 +13:00
background_color: val(&comment, "author_flair_background_color"),
foreground_color: val(&comment, "author_flair_text_color"),
},
distinguished: val(&comment, "distinguished"),
},
2021-02-15 11:53:09 +13:00
score: if data["score_hidden"].as_bool().unwrap_or_default() {
("\u{2022}".to_string(), "Hidden".to_string())
2021-02-01 11:10:13 +13:00
} else {
format_num(score)
},
rel_time,
created,
2021-02-15 11:53:09 +13:00
edited,
2021-01-02 09:33:57 +13:00
replies,
highlighted,
2020-10-26 09:25:59 +13:00
});
}
2021-01-07 18:27:24 +13:00
comments
2020-10-26 16:57:19 +13:00
}