redsunlib/src/subreddit.rs

181 lines
5.4 KiB
Rust
Raw Normal View History

2020-10-26 09:25:59 +13:00
// CRATES
2021-01-17 12:13:34 +13:00
use crate::utils::*;
2020-10-26 09:25:59 +13:00
use askama::Template;
2021-02-14 12:02:38 +13:00
use tide::{http::Cookie, Request};
2021-01-30 20:00:00 +13:00
use time::{Duration, OffsetDateTime};
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),
2021-01-09 14:35:04 +13:00
prefs: Preferences,
2020-10-26 09:25:59 +13:00
}
2021-01-02 19:21:43 +13:00
#[derive(Template)]
#[template(path = "wiki.html", escape = "none")]
struct WikiTemplate {
sub: String,
wiki: String,
2021-01-03 07:58:21 +13:00
page: String,
2021-01-11 10:08:36 +13:00
prefs: Preferences,
2021-01-02 19:21:43 +13:00
}
2020-11-20 10:49:32 +13:00
// SERVICES
pub async fn page(req: Request<()>) -> tide::Result {
// Build Reddit API path
let subscribed = cookie(&req, "subscriptions");
let front_page = cookie(&req, "front_page");
let sort = req.param("sort").unwrap_or_else(|_| req.param("id").unwrap_or("hot")).to_string();
2021-02-14 12:02:38 +13:00
let sub = req.param("sub").map(String::from).unwrap_or(if front_page == "default" || front_page.is_empty() {
if subscribed.is_empty() {
"popular".to_string()
} else {
2021-02-14 12:02:38 +13:00
subscribed.to_owned()
}
} else {
front_page.to_owned()
});
let path = format!("/r/{}/{}.json?{}&raw_json=1", sub, sort, req.url().query().unwrap_or_default());
2021-01-01 12:54:13 +13:00
2021-01-02 12:28:13 +13:00
match fetch_posts(&path, String::new()).await {
2021-01-08 05:38:05 +13:00
Ok((posts, after)) => {
2021-01-16 12:05:55 +13:00
// If you can get subreddit posts, also request subreddit metadata
let sub = if !sub.contains('+') && sub != subscribed && sub != "popular" && sub != "all" {
// Regular subreddit
2021-01-31 15:10:38 +13:00
subreddit(&sub).await.unwrap_or_default()
} else if sub == subscribed {
2021-01-31 17:24:09 +13:00
// Subscription feed
if req.url().path().starts_with("/r/") {
subreddit(&sub).await.unwrap_or_default()
} else {
Subreddit::default()
}
2021-01-31 17:24:09 +13:00
} else if sub.contains('+') {
// Multireddit
Subreddit {
name: sub,
..Subreddit::default()
}
2021-01-16 12:05:55 +13:00
} else {
Subreddit::default()
};
template(SubredditTemplate {
2021-01-08 05:38:05 +13:00
sub,
posts,
2021-01-02 12:28:13 +13:00
sort: (sort, param(&path, "t")),
2021-01-07 18:27:24 +13:00
ends: (param(&path, "after"), after),
2021-01-09 14:35:04 +13:00
prefs: prefs(req),
})
2021-01-02 19:21:43 +13:00
}
Err(msg) => error(msg).await,
2021-01-02 19:21:43 +13:00
}
}
2021-01-30 20:18:53 +13:00
// Sub or unsub by setting subscription cookie using response "Set-Cookie" header
pub async fn subscriptions(req: Request<()>) -> tide::Result {
let sub = req.param("sub").unwrap_or_default().to_string();
let query = req.url().query().unwrap_or_default().to_string();
let action: Vec<String> = req.url().path().split('/').map(String::from).collect();
2021-01-30 20:00:00 +13:00
let mut sub_list = prefs(req).subscriptions;
2021-01-30 20:00:00 +13:00
2021-02-10 18:56:38 +13:00
// Find each subreddit name (separated by '+') in sub parameter
for part in sub.split('+') {
// Modify sub list based on action
if action.contains(&"subscribe".to_string()) && !sub_list.contains(&part.to_owned()) {
// Add each sub name to the subscribed list
sub_list.push(part.to_owned());
// Reorder sub names alphabettically
sub_list.sort_by_key(|a| a.to_lowercase())
} else if action.contains(&"unsubscribe".to_string()) {
// Remove sub name from subscribed list
sub_list.retain(|s| s != part);
}
2021-01-30 20:00:00 +13:00
}
// Redirect back to subreddit
// check for redirect parameter if unsubscribing from outside sidebar
let redirect_path = param(format!("/?{}", query).as_str(), "redirect");
let path = if !redirect_path.is_empty() {
format!("/{}/", redirect_path)
} else {
format!("/r/{}", sub)
};
2021-02-14 12:02:38 +13:00
let mut res = redirect(path);
2021-01-30 20:18:53 +13:00
// Delete cookie if empty, else set
if sub_list.is_empty() {
// res.del_cookie(&Cookie::build("subscriptions", "").path("/").finish());
res.remove_cookie(Cookie::build("subscriptions", "").path("/").finish());
2021-01-30 20:18:53 +13:00
} else {
res.insert_cookie(
Cookie::build("subscriptions", sub_list.join("+"))
.path("/")
.http_only(true)
.expires(OffsetDateTime::now_utc() + Duration::weeks(52))
.finish(),
);
2021-01-30 20:18:53 +13:00
}
2021-01-30 20:00:00 +13:00
Ok(res)
2021-01-30 20:00:00 +13:00
}
pub async fn wiki(req: Request<()>) -> tide::Result {
let sub = req.param("sub").unwrap_or("reddit.com").to_string();
let page = req.param("page").unwrap_or("index").to_string();
2021-01-12 07:33:42 +13:00
let path: String = format!("/r/{}/wiki/{}.json?raw_json=1", sub, page);
2021-01-02 19:21:43 +13:00
2021-01-23 22:48:33 +13:00
match request(path).await {
Ok(res) => template(WikiTemplate {
sub,
2021-02-10 18:56:38 +13:00
wiki: rewrite_urls(res["data"]["content_html"].as_str().unwrap_or_default()),
page,
prefs: prefs(req),
}),
Err(msg) => error(msg).await,
2020-11-18 13:03:28 +13:00
}
2020-10-26 09:25:59 +13:00
}
// SUBREDDIT
2021-01-15 06:53:54 +13:00
async fn subreddit(sub: &str) -> Result<Subreddit, String> {
2020-11-19 15:50:59 +13:00
// Build the Reddit JSON API url
2021-01-12 13:44:31 +13:00
let path: String = format!("/r/{}/about.json?raw_json=1", sub);
2020-10-26 09:25:59 +13:00
2021-01-02 12:28:13 +13:00
// Send a request to the url
2021-01-23 22:48:33 +13:00
match request(path).await {
2021-01-02 12:28:13 +13:00
// If success, receive JSON in response
2021-01-02 19:21:43 +13:00
Ok(res) => {
// Metadata regarding the subreddit
let members: i64 = res["data"]["subscribers"].as_u64().unwrap_or_default() as i64;
let active: i64 = res["data"]["accounts_active"].as_u64().unwrap_or_default() as i64;
2020-11-20 17:42:18 +13:00
2021-01-02 19:21:43 +13:00
// Fetch subreddit icon either from the community_icon or icon_img value
2021-02-14 12:02:38 +13:00
let community_icon: &str = res["data"]["community_icon"].as_str().map_or("", |s| s.split('?').collect::<Vec<&str>>()[0]);
let icon = if community_icon.is_empty() { val(&res, "icon_img") } else { community_icon.to_string() };
2020-10-26 09:25:59 +13:00
2021-01-02 19:21:43 +13:00
let sub = Subreddit {
name: val(&res, "display_name"),
title: val(&res, "title"),
description: val(&res, "public_description"),
2021-02-10 18:56:38 +13:00
info: rewrite_urls(&val(&res, "description_html").replace("\\", "")),
2021-01-12 14:47:14 +13:00
icon: format_url(icon.as_str()),
2021-01-02 19:21:43 +13:00
members: format_num(members),
active: format_num(active),
wiki: res["data"]["wiki_enabled"].as_bool().unwrap_or_default(),
};
2020-12-24 17:36:49 +13:00
2021-01-02 19:21:43 +13:00
Ok(sub)
}
// If the Reddit API returns an error, exit this function
Err(msg) => return Err(msg),
}
2020-11-30 15:50:29 +13:00
}